Rails 5 Timestamps Will Be Changed

Rails 5 timestamps will be changed

If you are running Rails 4.2, you will notice the generated migration add a default option to timestamps:

1
2
3
4
5
6
7
8
class CreateFoods < ActiveRecord::Migration
  def change
    create_table :products do |t|

      t.timestamps null: false
    end
  end
end

Without the null: false it will emit a warning:

1
2
3
'#timestamp' was called without specifying an option for `null`. In Rails 5, this behavior will
 change to `null: false`. You should manually specify 'null: true' to prevent the behavior of
 your existing migrations from changing.

This null option is:

:null - allows or disallows NULL values in the column. This option could have been named :null_allowed.

null: false means you cannot give NULL values for created_at and updated_at on Rails 5.

So far so good, That’s it!!! See ya!!! :)

Where Should I Put My Code in Ruby on Rails Application?

Ruby on Rails Nested Form Fields

Sometimes you’re sure that’s not the right place for that piece of code, but where does it go? “Refactor” is only a good answer if you know how to fix it.

In a Rails application, and what kind of code goes where?

Models
For code about your database or domain objects, the model is your first step in Rails. Models are powerful, easy to test, reusable across applications and more like non-Rails code than most of Rails — familiar, even if you don’t know Rails yet.

If there’s a good way to put the code in your model, that’s usually a safe bet and a good idea.

Write tests too, of course!

Controllers
It’s easy to put lots of code in your controllers, but it’s almost always a mistake. Business logic for your app should get out of the controller and into the model as quickly as possible. Logic about how things are shown to the user should go into the view. In general, the controller should be a tiny, thin glue layer putting together your other components.

Views
Having lots of logic in your views is a huge anti-pattern. Don’t do it. It’s hard to test, it’s hard to find, it’s hard to write sandwiched in between the HTML… Just don’t.

Instead, your views should contain HTML, variables that turn into HTML, and calls to helper methods that generate HTML — or whatever your final output format is. There should be no logic in there to test. No conditionals, no loops, no non-display methods. If you add an output format, there should be no code to repeat because all the interesting data transforms already happened, and no other output format cares about your HTML-only helpers. Right?

Helpers
Rails “helpers” are very specifically view helpers. They’re automatically included in views, but not in controllers or models. That’s on purpose.

Code in the application helper is included in all the views in your application. Code in other helpers is included in the corresponding view. If you find yourself writing big loops, method calls or other logic in the view but it’s clearly display logic, move it into a method in the helper.

Lib Directory
Every Rails app starts with a /lib directory, but not much explanation of it.

Remember that helpers are specifically view helpers? What if you wanted a controller helper? Or a model helper? Sometimes you can use a parent controller or parent model, but that’s not always the best choice.

If you want to write a helper module for non-view logic, the /lib directory is usually the best place to put it. For example, logging code or some kinds of error handling may be a cross-cutting concern like that.

Also, if you’re putting everything in the ApplicationController or ApplicationHelper, those can get big. Consider factoring some of that code out into helpers, or into /lib.

Stuff in /lib isn’t always automagically included for you like controllers and models. So you may need to explicitly require the file, not just use the name of the class. (Autoload All Files in Lib Directory Ruby on Rails)

Gems
Sometimes you have reusable pieces in your application. A controller or model might be needed by multiple different Rails apps. A particular piece of logic for logging or display might be useful to a lot of different folks. You might even find a different way of doing things that most Rails apps would benefit from.

These are all cases where you want to create a new gem and have your applications use it instead of sharing a directory of code.

These days it’s really easy to create a new gem, so don’t be intimidated. If you haven’t worked through the first free chapter of Rebuilding Rails, this may be a good time to do it — it’ll show you how to quickly, easily create and use a new gem.

Assets
In a few cases, you’re not even writing Ruby code. Instead, it may be Sass, Scss, JavaScript or CoffeeScript. In this case, it generally belongs under app/assets.

Concerns and Exceptions
Rails has a very specific, very unusual setup. I think it’s a good idea for small apps, but only use Rails until it hurts. If your application gets too big or complicated, the Rails code organization may hurt more than it helps you.

There are several “grow out of Rails” approaches to apply alternate architectures to the framework. From Hexagonal Rails to Objects on Rails to the more general Clean Ruby DCI approach. I won’t tell you which to use, but I’ll tell you that you’re better off starting with plain, simple Rails and growing out of it.

Most Rails apps, and even more Rails controllers, don’t need to get all that big. They often don’t need to change much. Why go complicated when simple is working great?

So far so good, That’s it!!! See ya!!! :)

Ruby on Rails Nested Form Fields

Ruby on Rails Nested Form Fields

It’s super common to want to edit records along with their has_many associations on a single page.

This Rails gem helps creating forms for models with nested has_many associations and relies on jQuery to dynamically add and remove nested form fields without a page reload.
- Works for arbitrarily deeply nested associations (tested up to 4 levels).
- Works with form builders like simple_form.
- Requires at least Ruby 1.9 and the Rails asset pipeline.

To install, add nested_form_fields to your application’s Gemfile:

Gemfile
1
gem 'nested_form_fields'

Run bundle intall to install the gem:

1
bundle install

In application.js file add:

application.js
1
//= require nested_form_fields

assuming that you have a User model with nested videos:

user.rb
1
2
3
4
class User < ActiveRecord::Base
  has_many :videos
  accepts_nested_attributes_for :videos, allow_destroy: true
end

Use the nested_fields_for helper inside your user form to add the video fields:

1
2
3
= form_for @user do |f|
  = f.nested_fields_for :videos do |ff|
    = ff.text_field :video_title

Links to add and remove fields can be added using the add_nested_fields_link and remove_nested_fields_link helpers:

1
2
3
4
5
= form_for @user do |f|
  = f.nested_fields_for :videos do |ff|
    = ff.remove_nested_fields_link
    = ff.text_field :video_title
  = f.add_nested_fields_link :videos

Note that remove_nested_fields_link needs to be called within the nested_fields_for call and add_nested_fields_link outside of it via the parent builder.

So far so good, That’s it!!! See ya!!! :)

Ruby Hooks for Metaprogramming

Ruby Hooks for Metaprogramming

Overview

What is a Hook?
In programming, a hook is a place and usually an interface provided in packaged code that allows a programmer to insert customized programming. For example, a programmer might want to provide code that analyzed how often a particular logic path was taken within a program.

Ruby Hooks

Ruby lets you hook in and change a lot of behavior of the core language. Methods, constants, classes, variables… etc. Ruby lets you query them all, and change a lot about them.

Here’s summaries and links for all the hooks I could find:

Methods
- respond_to_missing? - A way to make sure your dynamic methods defined with method_missing also handle respond_to?
- method_missing - Called when a method cannot be found, potentially to allow dynamically defining one instead.
- method_added - Called whenever a method is added which can be used to modify the method.
- method_removed - Called whenever a method is removed.
- singleton_method_added - Method added to the singleton class of the object, to be callable just on this one instance.
- singleton_method_removed - Method removed from singleton class.
- method_undefined - A method has been undefined, with undef_method. Undef_method is different from remove_method because remove_method may still allow superclasses to define the method – undef_method means it’s gone entirely.
- singleton_method_undefined - Called when a singleton method is undefined entirely.
- initialize_copy - An optional callback when cloning any Object.

Classes
- inherited - A Ruby class is subclassed.

Modules
- append_features - A Module is included, and its constants, methods and variables used.
- included - A Module is included, which usually obsoletes “append_features”.
- extend_object - A Module extends an Object.
- extended - An Object is extended by a module, which mostly obsoletes extend_object.
- const_missing - A constant isn’t already present.

Marshalling
- marshal_dump - Called on an object to have it dump itself in Ruby Marshal format.
- marshal_load - Called on an object to have it load itself in Ruby Mashal format.

Coercion
- coerce - Called by the first type in a two-argument operator on the second argument, to make it turn into something the first argument can recognize.
- induced_from - Deprecated, please don’t use.
- to_i, to_f, to_s, to_a, to_hash, to_proc and others - Conversions, indicating that the object is being used as a type and should try to convert itself to that type.

Ruby on Rails Callback Classes

Ruby on Rails Callback Classes

If you want to reuse callback code for more than one object that Rails provides a way to write callback classes. All you have to do is pass a given callback queue an object that responds to the name of the callback and takes the model object as a parameter.

1
2
3
4
5
6
class MarkDeleted
  def self.before_destroy(model)
    model.update_attribute(:deleted_at, Time.current)
    false
  end
end

The behavior of MarkDeleted is stateless, so I added the callback as a class method.

1
2
3
class Account < ActiveRecord::Base
  before_destroy MarkDeleted
end
1
2
3
class Invoice < ActiveRecord::Base
  before_destroy MarkDeleted
end

So far so good, That’s it!!! See ya!!! :)

Ruby on Rails Currency Formatting

Ruby on Rails Currency Formatting

Well, Ruby on Rails framework provide some various ways for formatting currency. Formatting a number as currency is pretty easy thanks to the number_to_currency helper. This helper will take a valid number and format it as currency. It accept a number of different options that allow complete customization of the displayed value:

1
number_to_currency(number, options = {})
Options Description
:locale The locale option allows you to specify the locale you wish to use. Defaults to the current locale.
:precision Sets the level of precision. Defaults to 2. Precision is the number of decimal places after the decimal.
:unit Sets the denomination of the currency. example: $ for the United States.
:separator Specifies the separator to use between the units. example the “.” separates dollars and cents in the US.
:delimiter Specifies the separator to use for the thousands delimiter. example: 123,456.
for For loop.
:format Sets the format for non-negative numbers. The current default is “%u%n”. The %u specifies the currency (“$”) and the %n specifies the number (“123,456”)
:negative_format Same as format, but applies to negative numbers.
:raise If raise is set to true, an exception will be raised if the number isn’t a valid number.


Example:

1
2
3
4
5
6
7
8
number_to_currency 123456.50                        # => $123,456.50
number_to_currency 123456.506                       # => $123,456.51
number_to_currency 123456.506, precision: 3         # => $123,456.506
number_to_currency "123a456"                        # => $123a456
number_to_currency "123a456", raise: true           # => ActionView::Helpers::NumberHelper::InvalidNumberError error
number_to_currency -123456.50, :negative_format => "(%u%n)"                               # => ($123,456.50)
number_to_currency 123456.50, unit: "£", seperator: ",", delimiter: ""                    # => £123456.50
number_to_currency 123456.50, unit: "£", separator: ",", delimiter: "", format: "%n %u"   # => 123456,50 £

So far so good, That’s it!!! See ya!!! :)

Dependency Inversion Principle in Ruby

Dependency Inversion Principle in Ruby

Simply Dependency Inversion Principle states that: Abstractions should not depend upon details. Details should depend upon abstractions.

Let’s go back to the first example on the Open/Closed Principle and change it a bit:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Report
  def body
    generate_reporty_stuff
  end

  def print
    JSONFormatter.new.format(body)
  end
end

class JSONFormatter
  def format(body)
    ...
  end
end

Now there is a formatter class, but I’ve hardcoded it on the Report class, thus creating a dependency from the Report to the JSONFormatter. Since the Report is a more abstract (high-level) concept than the JSONFormatter, we’re effectively breaking the DIP.

We can solve it the exact same way with solved it on the Open/Closed Principle problem, with dependency injection:

1
2
3
4
5
6
7
8
9
class Report
  def body
    generate_reporty_stuff
  end

  def print(formatter: JSONFormatter.new)
    formatter.format body
  end
end

So far so good, this way the Report does not depend on the JSONFormatter and can use any type of formatter that has a method called format (this is known as duck typing). That’s it!!! See ya!!! :)

Interface Segregation Principle in Ruby

Interface Segregation Principle

Simply Interface Segregation Principle states that: When a client depends upon a class that contains interfaces that the client does not use, but that other clients do use, then that client will be affected by the changes that those other clients force upon the class.

If you have a class that has two clients (objects using it):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Car
  def open
  end

  def start_engine
  end

  def change_engine
  end
end

class Driver
  def drive
    @car.open
    @car.start_engine
  end
end

class Mechanic
  def do_stuff
    @car.change_engine
  end
end

As you can see, our Car class has an interface that’s used partially by both the Driver and the Mechanic. We can improve our interface like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Car
  def open
  end

  def start_engine
  end
end

class CarInternals
  def change_engine
  end
end

class Driver
  def drive
    @car.open
    @car.start_engine
  end
end

class Mechanic
  def do_stuff
    @car_internals.change_engine
  end
end

So far so good, splitting the interface into two, we can comply to the Interface Segregation Principle. That’s it!!! See ya!!! :)

Liskov Substitution Principle in Ruby

Liskov Substitution Principle in Ruby

Assume that we already had the code:

1
2
3
4
5
6
7
8
9
10
11
class Animal
  def walk
     do_some_walkin
  end
end

class Cat < Animal
  def run
    run_like_a_cat
  end
end

This principle applies only to inheritance. In order to comply with the Liskov Substitution Principle, Subtypes must be substitutable for their base types.

Well, so they must have the same interface. Since ruby does not have abstract methods, we can do it like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Animal
  def walk
    do_some_walkin
  end

  def run
    raise NotImplementedError
  end
end

class Cat < Animal
  def run
    run_like_a_cat
  end
end

So far so good, That’s it!!! See ya!!! :)

Open/Closed Principle in Ruby

Open/Closed Principle in Ruby

Assume that we already had the code:

1
2
3
4
5
6
7
8
9
class Report
  def body
    generate_reporty_stuff
  end

  def print
    body.to_json
  end
end

The code above violates Open/Closed Principle as if we want to change the format the report gets printed, we need to change the code of the class. Let make it be better then:

1
2
3
4
5
6
7
8
9
class Report
  def body
    generate_reporty_stuff
  end

  def print(formatter: JSONFormatter.new)
    formatter.format body
  end
end

This way changing the formatter is as easy as:

1
2
report = Report.new
report.print(formatter: XMLFormatter.new)

So far so good, I have extended the functionality without modifying the code. In this example, I have used a technique called “Dependency Injection”. That’s it!!! See ya!!! :)