RSS
 

Archive for the ‘Programming’ Category

ChatGPT: What is the common way to parse command line parameters with Rust?

04 Mar

Rust Programming Language logoIn Rust, the most common way to parse command-line parameters is by using the std::env::args function, which returns an iterator over the command-line arguments passed to the program. Read the rest of this entry »

 

Ruby RSpec FactoryBot traits and transient via ChatGPT

15 Dec

The following was edited together from a series of questions to ChatGPT on the topic. Currently, I cannot identify sources of the originating content. My role was to edit ChatGPT into the following.

FactoryBot

RSpec is a testing framework for the Ruby programming language, and FactoryBot (formerly known as Factory Girl) is a library for creating test data in Ruby. Together, these tools can be used to write unit-tests for a Ruby application.

In FactoryBot, a factory is a blueprint for creating test data objects. A factory can define various attributes of the objects it creates, such as the object’s type, the values of its attributes, and any associations it has with other objects.

Read the rest of this entry »
 
 

Frontend Security Recipe Checklist

03 Jan

Even as the number of frontend programming vulnerabilities grows continually, many are not difficult to combat; you simply need to remember to fortify your frontend security against them.

 
 

ReactJS: componentWillReceiveProps() is Dead! (*sniff*)

21 Apr

ReactJSThings evolve. ReactJS evolves. With version 16.3, there were several changes to the component life-cycle methods. In particular, componentWillReceiveProps is disappearing. In its place, they say, you can use the getDerivedStateFromProps static function. I found this a bit challenging, but I did find an interesting pattern when the component-state was dependent on fetched information.

I should mention that I had a specific goal to better encapsulate data within the component. While I could pass in all the needed data as properties, that would require the surrounding component know what to pass and how to get it. That shouldn’t necessarily be necessary; the component knows what it needs and how to retrieve it.

For example, say you have a component which accepts a phone number and displays the phone number and the state that it’s from. Certainly, you could write a simple component that accepts both pieces of information as properties.

<ShowPhoneLocation number="+12065551212" city="Seattle" />

Which might be implemented as:

class ShowPhoneLocation extends React.Component {
  render() {
    return (
      <div>{this.props.number} is from {this.props.city}</div>
    )
  } // render()
} // class ShowPhoneLocation

But, since the component should be able to infer the state from the phone number (by its area code), it shouldn’t be incumbent on its container to know what it is.

class ShowPhoneLocation extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    let location = getCityFromPhone(nextProps.number)
    return {
      city: location
    }
  }
  render() {
    return (
      <div>{this.props.number} is from {this.state.city}</div>
    )
  } // render()
} // class ShowPhoneLocation

That’s all well and good, but what if getCityFromPhone() has to call a web service? We don’t want getDerivedStateFromProps() to stall, waiting for a response. However, it is static and does not have a this reference to the object for which it is returning state; so an asynchronous fetch doesn’t know what object’s state to set. Instead, don’t wait for the result to save in the state, save the request’s Promise in the state and update the state, once the promise resolves.

function getCityFromPhone(number) {
  return fetch('http://saas.com/get/'+number+'/city') // Returns fetch promise
}
class ShowPhoneLocation extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    let location = getCityFromPhone(nextProps.number)
    return {
      city: location
    }
  }
  componentDidUpdate() {
    let location = this.state.city
    if (location instanceof Promise) {
      this.setState({ city: '...waiting...' })
      location.then(city => this.setState({ city: city }) )
        .catch(() => this.setState({ city: 'not found' }) )
    }
  }
  render() {
    return (
      <div>
        {this.props.number} is from {this.state.city instanceof Promise
         ? '...'
        : this.state.city}</div>
    )
  } // render()
} // class ShowPhoneLocation

In componentDidUpdate() you can define the completion handlers to set the object’s state, base on the returned information from the service.

It is a common pattern to perform a fetch in componentDidMount(). The problem is that there may not be enough information to perform the fetch, that early, or the information for the fetch changes after the component has been mounted.

I am going to miss componentWillReceiveProps()… without it, things become a bit more convoluted but it’s going the way of the Dodo.

 

Promises, Promises… Timeout!

25 Apr

I was playing with ES6’s new Promises, for the first time, this week. Then, I was looking at the ugliness of using a browser’s setTimeout() function and thought that it would look better as a Promise.

tl;dr summary: A Simple Promise Version of “setTimeout()”

If we do it right, you simply specify the timeout period and implement a handler for then() to invoke:

timeout(5000) // Delay for 5000 ms
   .then(function () {
      // Do, here, whatever should happen when the time has elapsed…
   });

Or, since this is ES6, we might as well use arrow-function shorthand:

timeout(5000).then( () => {
   // do your thing, here…
})

Implementation

The setTimeout() already functions a bit like a Promise, without matching the promise-pattern and syntax, so converting it to a Promise is pretty easy: Read the rest of this entry »

 
 

Simplicity via PHP Frameworks

05 Apr

PHP language and web-technologyA long time ago, I’d endeavored to create my own lightweight PHP framework, ccPHP. It was a good exercise, but never reached prime time. Around that time I began to notice others endeavoring to do the same thing (i.e., create simpler, lighter weight PHP frameworks that didn’t take more time to learn than to implement the project). I’ve been away for a while and things have changed.

  1. The continued refinement and simplification of frameworks.
  2. The greater emphasis on frontend apps to do more of the work that used to be done in the middle tier.
  3. The ubiquity of RESTful interfaces, the dividing line between front-ends and servers.

Micro-PHP Frameworks

I doubt that I will ever finish my own framework, now that others are a lot closer to the goals that I was moving towards. And, right now, I simply want to find a lightweight modular frameworks that truly help me get my core work done. Dragan Gaic did a great survey of the PHP hot frameworks in Top 12 Best PHP RESTful Micro Frameworks (Pro/Con).

A key feature of such frameworks is for them to be modular to allow me to pick and choose only the components I need, rather than have to install, understand, and run a bunch of functionality that I do not need. It makes it harder for the developer and impacts performance of the results. Model-View-Controler (MVC) is a common software architecture pattern. With the client side being far more capable of managing the view part, on its own, the server side can be simpler. Instead of cluttering up the server-side app with trying to display information, it can simply focus on securing data and access and providing data services via RESTful interfaces.

So, what I am looking for are pieces to help me access persistent data and build RESTful interfaces. And something to help keep all the code flow organized. Based on the article, I can look at Silex, Slim, Lumen, or Phalcon for the latter. For database access, Ive worked with RedBeans before and liked it, so I will probably pick that up again. If one of the frameworks doesnt help implement and configure a RESTful interface simply, then I may get back into the framework building business again.

Model: RedBeans
View: Frontend client
Controler: one of Silex, Slim, Lumen, or Phalcon

A WordPress bug allowed my website to be hacked. I thought this was lost forever until I thought to reconstitute it from http://Archive.org!!

 

Activating OS X’s Builtin Apache Web Server and PHP

14 Jan

As I mentioned in my prior post OS X Command-line Dev Tools—Install Shortcut, OS X comes with a variety of built-in tools suited for developers. Unfortunately, Apple has seen fit to hide one of the most important of them: the web server. Despite that, they are easily unlocked if you know how. This applies to Mountain Lion (10.8) and (though I haven’t tried it, yet) Mavericks (10.9). Though you can install separate installations, I don’t like to install anything extra, unless I must. Read the rest of this entry »

 

PHP Recipe to Show Source-code

19 Nov

PHP source-code display recipeHere is a simple Web 1.5 (static HTML with a little bit of styling and JavaScript) recipe to allow a viewer of your web page to see the PHP source-code, behind it, with a minimal amount of JavaScript and a little CSS manipulation—good for showing the work you’ve done to others. Or for embedding in your own source, in debug mode, so that teammates can see each others’ work.

See the example code at: http://cachecrew.com/sample_code/highlight_file.php and http://cachecrew.com//sample_code/highlight_file2.php.

The PHP and HTML Read the rest of this entry »

 

OS X Command-line Dev Tools—Install Shortcut

12 Nov

Xcode command-line toolsAmong those around me, in world of tech startups (even in the vicinity of the world of Windows), MacBooks are used almost universally. I can’t explain the discrepancy between what I see around me and the data you usually read; but I do know that as a technical platform, OS X provides an easier path to development tools. These days, the world driven by web-based applications. A majority of those applications run on Linux-based machines. OS X shares with Linux, a common ancestor, Unix. So, a robust array of common commands come with OS X—ssh, ftp, bash, vi, emacs, etc. But more importantly, OS X comes pre-installed with hottest development tools used for web development, today—Ruby, Python, PHP, Apache, memcache, etc. This means a developer can write web applications without even being connected to the Internet!

There are more tools available with the free download of Xcode, Read the rest of this entry »

 

Self-documenting Bash Scripts Using Heredoc

22 Jul

It is surprising how quickly we forget how to use scripts we had written, let alone, what they were for. So it is even more difficult for others to know how and whether to use your script. You can avoid wasting the efforts you put into the problems you solved with your script by simply adding some friendly “help” output.

Here is some basic information you should include:

  • Summary description
  • Form of use—basic syntactic usage
  • Description of usage syntax; i.e., input parameters
  • More detailed information, if necessary. Read the rest of this entry »