How to Create Rails Environment [Solved]

How to Create Rails Environment

Ruby on Rails LogoWhen David Heinemeier Hansson (DHH) was developing Basecamp and creating the Rails framework, he most definitely faced the problem of “how do I separate the configuration and environment settings for development and production deployments of the application”. Mainly, the big issue, when I was be coding, was keeping the configuration for the development and production database easily accessible and swappable. I would say that all (99.999%) of software developers have faced this problem and created/found solutions to help solve it.

Rails offers an elegant solution to this challenge, by providing you with a way to separate these environment into separate configuration files.

Understanding The Environments

Rails comes with concept of separating the environments that you application will be executed in. When you develop you application you are said to be in the DEVELOPMENT environment, when you run your tests you are in the TEST environment and when you deploy you server to production the code is run in the PRODUCTION environment.

Database Environments

This can be easily seen in the default database configuration file, generated when you create a Rails application.

“` yaml

adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000

Warning: The database defined as “test” will be erased and

re-generated from your development database when you run “rake”.

Do not set this db to the same as development or production.

adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000

adapter: sqlite3
database: db/production.sqlite3
pool: 5
timeout: 5000


As you can tell, the default database is SQLite3 and Rails generates names for you database, which are closely related to the environment name.

If you create Rails application with MySQL as the default database, the names generated for you will follow this format.

adapter: mysql2
encoding: utf8
reconnect: false
database: myapp_production
pool: 5
username: root
socket: /tmp/mysql.sock

So the pattern will be ‘yourapplicationname’ with ‘enviromentname’ appended to it. This pattern is commonly accepted by the Rails Developers and I suggest you don’t change it, unless you are working with a legacy database, in which case only your production database name should change.

** TIP: ** leave your development and test database names unchanged, they will not affect how your application is developed and tested and make sure the other developers working on the same app don’t need to modify the settings on their own computer.

** TIP: ** For simplicity’s sake, I would by default use SQLite3 as the test and development database.

Application Environments

Inside every Rails app, inside the config directory, there exists an environments directory. This is a place where application settings specific to an environment are defined.

By default, three files are generated there:

  • development.rb
  • production.rb
  • test.rb

Each file contains a set of configuration options that define how a Rails application is to be executed.

“` ruby
School::Application.configure do
# Settings specified here will take precedence over those in config/application.rb

# In the development environment your application’s code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don’t have to restart the webserver when you make code changes.
config.cache_classes = false

# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true

# Show full error reports and disable caching
config.considerallrequestslocal = true
view.debugrjs = true
controller.perform_caching = false

# Don’t care if the mailer can’t send
config.actionmailer.raisedelivery_errors = false

# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log

# Only use best-standards-support built into browsers
config.actiondispatch.beststandards_support = :builtin

This is an example of a development.rb environment configuration file. Some of the settings included here are:

  • whiny_nils – ensures that errors on nil objects are logged
  • actionmailer.raisedelivery_errors is set to false – don’t tell me that emails can’t be delivers, since its a develoment environment
  • disable cache – makes every class be reloaded on each request

The production.rb file for the production environment, is much more stricter and enables caching, hides some of the nasty errors from being displayed to the user and generally makes your application run faster.

In the test enviroment, test.rb resembles the development.rb since you want error messages to be available and logged for debugging purpose, however, it performs some caching to make tests run faster.

Every generated environment file includes this commented line at the top of the file.

“` ruby

Settings specified here will take precedence over those in config/application.rb


This means that you are able to create application wide settings in the application.rb file and then override it based on which environment your application is in.

Running The App in Different Environments

A Rails application determines on its own, which environment it should be running in. It looks for an environmental variable RAILS_ENV to tell it which environment it should run in. If the variable is empty or does not exist, it runs using the settings for the DEVELOPMENT environment.

You can start a Rails server in a specific environment by setting the RAILS_ENV variable.

$ RAILS_ENV=production
$ rails s

This will start the Rails app in the production environment.

When you run your Tests using rake test command, Rake automatically sets the environment to TEST, you don’t have to do anything.

** TIP: ** You might be tempted to run a rails server in the TEST environment. DON’T DO IT. The TEST environment is only for testing.

When you application is deployed on the production server, the setting of the PRODUCTION environment is done through PassengerMod (For apache) or NginX (EngineX) server. Usually, they treat any application deployed with either of these as being in PRODUCTION environment, so you don’t have to do anything extra. If you want to specifically change the environment, you can do so using one of their configuration directives (see their documentation).

Creating Custom Environments

Sometimes you want to create a custom environment. Personally, I only see it useful to have a STAGING environment, an exact copy of PRODUCTION. This serves only as a naming distinction. You might have other reasons, but I would suggest keeping everything as default, they are good enough for most projects.

So, to create a new environment for your rails application, just copy and past one of the environment files inside config/environments directory, rename it to the environment you want. Then add an environment definition to the config/database.yml for that environment and you are ready to roll.

Example of database.yml:

“` yaml

database config

adapter: mysql2
encoding: utf8
reconnect: false
database: myapp_staging
pool: 5
username: someuser
password: somepassword
socket: /tmp/mysql.sock



This was a brief explanation of how environments work and why they are there. If I missed something, don’t hesitate to ask questions in the comments.


How to Use Multiple Table Inheritance in Rails [Solved]

How to Use Multiple Table Inheritance in Rails

Ruby-on-RailsIt is a fact that sometimes we want to achieve a database design similar to the design of classes and subclasses in OOP. This design is what we call Multiple Table Inheritance (MTI). The idea behind it is to have a main table which will hold all the basic attributes of the underlying models and separate tables for the underlying models each of them will hold specific attributes special for each model.

Multiple Table Inheritance – Rails 3 Implementation

Enough of the theory, let’s get our hands dirty and make it work in the Rails framework. For our purposes let us suppose that we have two (for simplicity) different types of businesses: restaurants and bars. Both are businesses and both share same attributes such as: name, address, phone number, etc. But if you look closely you will see that a restaurant and a bar have also many different attributes (has waiter, has wifi, has kids area etc. for the restaurant, music type, best nights, dresscode etc. for the bar). So it is best to have a common table that holds all the common attributes and separate tables to hold all the different ones i.e. Multiple Table Inheritance. Following this design you remove duplication from the database and at the same you keep tables clean (without many many NULL values).

multiple table inheritance rails 3

Multiple Table Inheritance – Models

We will create a base model

  1. classBusiness<ActiveRecord::Base
  2. # ASSOCIATIONS ——————————————————–
  3. belongs_to :biz,:polymorphic =>true
  4. end

that it will hold all of the common attributes and it will be polymorphic as it will contain content from different models (Restaurant, Bar etc). Next we define the other two models

  1. classRestaurant<ActiveRecord::Base
  2. acts_as_biz
  3. end
  1. classBar<ActiveRecord::Base
  2. acts_as_biz
  3. end

which both contain only the acts_as_biz class method. We intend to use this method in order to give to models some shared functionality. First we want to make the Business model transparent (as it is now an intermediate model) i.e. we want to call the Business attributes directly on the Restaurant / Bar instance e.g.

  1. bar
  2. # => #<Bar id: nil, music: nil, best_nights: nil, dresscode: nil>
  4. # => nil

Multiple Table Inheritance – Mixins

To accomplish that we have to do two basic things. Firstly we have to define attribute accessors (of the Business class) inside the acts_as_biz method and secondly we have to autobuild the association between Business and Restaurant / Bar whenever we initialize any child class. We do all that inside the following module:

  1. moduleBiz
  2. def acts_as_biz
  3. include InstanceMethods
  4. ############################ Class methods ################################
  5. has_one :business,:as=>:biz,:autosave =>true,:dependent =>:destroy
  6. alias_method_chain :business,:build
  7. business_attributes<– gives access to all columns of Business
  8. # define the attribute accessor method
  9. def biz_attr_accessor(*attribute_array)
  10. attribute_array.each do|att|
  11. define_method(att)do
  12. business.send(att)
  13. end
  14. define_method(“#{att}=”)do|val|
  15. business.send(“#{att}=”,val)
  16. end
  17. end
  18. end
  19. biz_attr_accessor *business_attributes #<- delegating the attributes
  20. end
  22. moduleInstanceMethods
  23. def business_with_build
  24. business_without_build || build_business
  25. end
  26. end
  27. end

Now, let us explain a little bit what’s going on here. The line

  1. has_one :business,:as=>:biz,:autosave =>true,:dependent =>:destroy

is self explanatory. Every Bar / Restaurant will have only one entry in the businesses table and when we destroy a Bar / Restaurant the entry in the businesses table must disappear too. Also we want to autosave the association for apparent reasons (that is why we have set autosave to true). Next we define the custom attribute accessor biz_attr_accessor that does the job of delegating the attribute accessors of the Business class to the Bar / Restaurant class. Now, as we said earlier, we have to autobuild the association and to do that we have to use the alias_method_chain approach as we have no control over the ActiveRecord::Base class. If you are not familiar of what the alias_method_chain does it is a shorter syntax of

  1. alias_method :business_without_build,:business
  2. alias_method :business,:business_with_build

Combining this with the method

  1. def business_with_build
  2. business_without_build || build_business
  3. end

we ensure the autobuilding of the association. Now that we have build the Biz module (and saved it into the /lib directory) we have to create an initializer, say biz_init.rb, and inside extend the ActiveRecord::Base i.e.

  1. ActiveRecord::Base.extend Biz

Multiple Table Inheritance – Conclusion

Closing I have to point out that it is best to follow the above approach when

  • Your models physically follow inheritance (you should NOT use it otherwise)
  • Your models have plenty common attributes but at the same time plenty uncommon. If it is not the case, you should probably have them in the same table (have little uncommon attributes) or in separate tables (have little common attributes).

Note: I want to say to those alias_method_chain haters and to those who prefer to use super instead, that despite the fact that using super is preferable, sometimes (when you have no control over some class) you have no alternative. I strongly advise you to read the best article I have found so far on the subject.


How to Use Blocks in Ruby [Solved]

How to Use Blocks in Ruby

Ruby-on-RailsYou have seen how Ruby defines methods where you can put number of statements and then you call that method. Similarly, Ruby has a concept of Block.

  • A block consists of chunks of code.
  • You assign a name to a block.
  • The code in the block is always enclosed within braces ({}).
  • A block is always invoked from a function with the same name as that of the block. This means that if you have a block with the name test, then you use the function test to invoke this block.
  • You invoke a block by using the yield statement.



Here, you will learn to invoke a block by using a simple yield statement. You will also learn to use a yield statement with parameters for invoking a block. You will check the sample code with both types of yield statements.

The yield Statement:

Let’s look at an example of the yield statement:

#!/usr/bin/rubydef test
   puts "You are in the method"yield
   puts "You are again back to the method"yieldend
test {puts "You are in the block"}

This will produce the following result:

You are in the method
You are in the block
You are again back to the method
You are in the block

You also can pass parameters with the yield statement. Here is an example:

#!/usr/bin/rubydef test
   puts "You are in the method test"yield100end
test {|i| puts "You are in the block #{i}"}

This will produce the following result:

You are in the block 5You are in the method test
You are in the block 100

Here, the yield statement is written followed by parameters. You can even pass more than one parameter. In the block, you place a variable between two vertical lines (||) to accept the parameters. Therefore, in the preceding code, the yield 5 statement passes the value 5 as a parameter to the test block.

Now, look at the following statement:

test {|i| puts "You are in the block #{i}"}

Here, the value 5 is received in the variable i. Now, observe the following puts statement:

puts "You are in the block #{i}"

The output of this puts statement is:

You are in the block 5

If you want to pass more than one parameters, then the yield statement becomes:

yield a, b

and the block is:

test {|a, b| statement}

The parameters will be separated by commas.

Blocks and Methods:

You have seen how a block and a method can be associated with each other. You normally invoke a block by using the yield statement from a method that has the same name as that of the block. Therefore, you write:

#!/usr/bin/rubydef test
test{ puts "Hello world"}

This example is the simplest way to implement a block. You call the test block by using the yield statement.

But if the last argument of a method is preceded by &, then you can pass a block to this method and this block will be assigned to the last parameter. In case both * and & are present in the argument list, & should come later.

#!/usr/bin/rubydef test(&block)
test { puts "Hello World!"}

This will produce the following result:


BEGIN and END Blocks

Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the program has finished executing (the END blocks).

#!/usr/bin/rubyBEGIN{# BEGIN block code 
  puts "BEGIN code block"}END{# END block code 
  puts "END code block"}# MAIN block code 
puts "MAIN code block"

A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered. END blocks are executed in reverse order. When executed, above program produces the following result:

BEGIN code block
MAIN code block
END code block


How to Use Private Member Variables in Ruby [Solved]

How to Use Private Member Variables in Ruby

Ruby-on-RailsIf you’re new to Ruby, especially if you’re coming from a Rails background, you probably use attr_accessor (if not outright adding columns to the table in Rails) to add member variables to a class. Like so:


class Player
attr_accessor :x, :y

What does this mean? It means you can do things like:

p =
p.x = 2;
p.y += 3;
puts "Player is at (#{p.x}, #{p.y})."

i.e. you get the ability to both read and write to x and y, for FREE–without any additional code. Smooth!

But, if you’re like me, you will probably reach a point where you want to add some member variables, but not make them publically accessible. How do you do it?

The answer is to use the @name convention, like so:

class Player
def initialize(x, y)
@x = x
@y = y

Unlike the attr_accessor code above, this does NOT allow you to do things like:

p =, 4)
puts "Player is at #{p.x}, #{p.y}" # raises an error: X and Y don't exist

But, as I mentioned, that’s what this is for–creating private member variables.

Also, realize that in Ruby, objects are very dynamic–you can add properties on the fly! We didn’t explicitly “declare” x and y anywhere in our Player class; yet we can access them.

And that, in a nutshell, is private member variables. One last thing to note–you can almost think of attr_accessor :some_thing as equivalent to:

class Whatever
@some_thing = nil
def some_thing
return @some_thing
def some_thing=(value)
@some_thing = value

But of course, all this is free by using attr_accessor. So use it!


How To Sanitize HTML In Rails That Actually Works [Solved]

How To Sanitize HTML In Rails That Actually Works

Ruby on Rails LogoAssuming you don’t want to simply escape everything, sanitizing user input is one of the relative weak points of the Rails framework. On SpeakerRate, where users can use Markdown to format comments and descriptions, we’ve run up against some of the limitations of Rails’ built-in sanitization features, so we decided to dig in and fix it ourselves.

In creating our own sanitizer, our goals were threefold: we want to let a subset of HTML in. As the Markdown documentation clearly states, “for any markup that is not covered by Markdown’s syntax, you simply use HTML itself.” In keeping with the Markdown philosophy, we can’t simply strip all HTML from incoming comments, so the included HTML::WhiteListSanitizer is the obvious starting point.

Additionally, we want to escape, rather than remove, non-approved tags, since some commenters want to discuss the merits of, say, <h2 class="h2">. Contrary to its documentation, WhiteListSanitizer simply removes all non-whitelisted tags. Someone opened a ticket about this issue in August of 2008 with an included patch, but the ticket was marked as resolved without ever applying it. Probably for the best, as the patch introduces a new bug.

Finally, we want to escape unclosed tags even if they belong to the whitelist. An unclosed <strong> tag can wreak havoc on the rest of a page, not to mention what a <div> can do. Self-closing tags are okay.

With these requirements in mind, we subclassed HTML::WhiteListSanitizer and fixed it up. Introducing, then:

HTML::StathamSanitizer. User-generated markup, you’re on notice: this sanitizer will take its shirt off and use it to kick your ass. At this point, I’ve written more about the code than code itself, so without further ado:

  1. module HTML
  2. classStathamSanitizer<WhiteListSanitizer
  4. protected
  6. def tokenize(text, options)
  7. do|token|
  8. if token.is_a?(HTML::Tag)&& options[:parent].include?(
  9. token.to_s.gsub(/</,“&lt;”)
  10. else
  11. token
  12. end
  13. end
  14. end
  16. def process_node(node, result, options)
  17. result <<case node
  18. when HTML::Tag
  19. if node.closing ==:close && options[:parent].first ==
  20. options[:parent].shift
  21. elsif node.closing !=:self
  22. options[:parent].unshift
  23. end
  25. process_attributes_for node, options
  27. if options[:tags].include?(
  28. node
  29. else
  30. bad_tags.include?( node.to_s.gsub(/</,“&lt;”)
  31. end
  32. else
  33. bad_tags.include?(options[:parent].first)?nil: node.to_s.gsub(/</,“&lt;”)
  34. end
  35. end
  36. end
  37. end


How to Program Inheritance using Ruby on Rails [Solved]

How to Program Inheritance using Ruby on Rails

Ruby on Rails LogoInheritance is a relation between two classes. We know that all cats are mammals, and all mammals are animals. The benefit of inheritance is that classes lower down the hierarchy get the features of those higher up, but can also add specific features of their own. If all mammals breathe, then all cats breathe. In Ruby, a class can only inherit from a single other class. Some other languages support multiple inheritance, a feature that allows classes to inherit features from multiple classes, but Ruby doesn’t support this.

We can express this concept in Ruby – see the p033mammal.rb program below:

  1. class Mammal
  2.   def breathe
  3.     puts “inhale and exhale”
  4.   end
  5. end
  6. class Cat < Mammal
  7.   def speak
  8.     puts “Meow”
  9.   end
  10. end
  11. rani =
  12. rani.breathe
  13. rani.speak

Though we didn’t specify how a Cat should breathe, every cat will inherit that behaviour from the Mammal class since Cat was defined as a subclass of Mammal. (In OO terminology, the smaller class is a subclass and the larger class is a super-class. The subclass is sometimes also known as a derived or child class and the super-class as base or parent class). Hence from a programmer’s standpoint, cats get the ability to breathe for free; after we add a speak method, our cats can both breathe and speak.

There will be situations where certain properties of the super-class should not be inherited by a particular subclass. Though birds generally know how to fly, penguins are a flightless subclass of birds. In the example p034bird.rb below, we override fly in class Penguin:

  1. class Bird
  2.   def preen
  3.     puts “I am cleaning my feathers.”
  4.   end
  5.   def fly
  6.     puts “I am flying.”
  7.   end
  8. end
  9. class Penguin < Bird
  10.   def fly
  11.     puts “Sorry. I’d rather swim.”
  12.   end
  13. end
  14. p =
  15. p.preen

Rather than exhaustively define every characteristic of every new class, we need only to append or to redefine the differences between each subclass and its super-class. This use of inheritance is sometimes called differential programming. It is one of the benefits of object-oriented programming.

The above two programs are taken from the online Ruby User’s Guide.

Thus, Inheritance allows you to create a class that is a refinement or specialization of another class. Inheritance is indicated with <.

Here’s another example, p035inherit.rb

  1.  class GF
  2.  def initialize
  3.   puts ‘In GF class’
  4.  end
  5.  def gfmethod
  6.   puts ‘GF method call’
  7.  end
  8. end
  9. # class F sub-class of GF
  10. class F < GF
  11.  def initialize
  12.   puts ‘In F class’
  13.  end
  14. end
  15. # class S sub-class of F
  16. class S < F
  17.  def initialize
  18.   puts ‘In S class’
  19.  end
  20. end
  21. son =
  22. son.gfmethod

A class can only inherit from one class at a time (i.e. a class can inherit from a class that inherits from another class which inherits from another class, but a single class can not inherit from many classes at once).

There are many classes and modules (more on this later) built into the standard Ruby language. They are available to every Ruby program automatically; no require is required. Some built-in classes are Array, Bignum, Class, Dir, Exception, File, Fixnum, Float, Integer, IO, Module, Numeric, Object, Range, String, Thread, Time. Some built-in modules are Comparable, Enumerable, GC, Kernel, Math.

The BasicObject class is the parent class of all classes in Ruby. Its methods are therefore available to all objects unless explicitly overridden. Prior to Ruby 1.9, Object class was the root of the class hierarchy. The new class BasicObject serves that purpose, and Object is a subclass of BasicObject. BasicObject is a very simple class, with almost no methods of its own. When you create a class in Ruby, you extend Object unless you explicitly specify the super-class, and most programmers will never need to use or extend BasicObject.

In Ruby, initialize is an ordinary method and is inherited like any other.

IN RAILS: Inheritance is one of the key organizational techniques for Rails program design and the design of the Rails framework.

Inheritance and Instance Variables

Consider the code:

  1. class Dog
  2.   def initialize(breed)
  3.     @breed = breed
  4.   end
  5.   def to_s
  6.     “(#@breed, #@name)”
  7.   end
  8. end
  9. class Lab < Dog
  10.   def initialize(breed, name)
  11.     super(breed)
  12.     @name = name
  13.   end
  14. end
  15. puts“Labrador”“Benzy”).to_s # .to_s is called implicitly with any puts or print or p method call

When you invoke super with arguments, Ruby sends a message to the parent of the current object, asking it to invoke a method of the same name as the method invoking super. super sends exactly those arguments.

The to_s method in class Lab references @breed variable from the super-class Dog. This code works as you probably expect it to:

  1. puts“Labrador”“Benzy”).to_s ==> (Labrador, Benzy)

Because this code behaves as expected, you may be tempted to say that these variables are inherited. That is not how Ruby works.

All Ruby objects have a set of instance variables. These are not defined by the objects’s class – they are simply created when a value is assigned to them. Because instance variables are not defined by a class, they are unrelated to subclassing and the inheritance mechanism.

In the above code, Lab defines an initialize method that chains to the initialize method of its super-class. The chained method assigns values to the variable @breed, which makes those variables come into existence for a particular instance of Lab.

The reason that they sometimes appear to be inherited is that instance variables are created by the methods that first assign values to them, and those methods are often inherited or chained.

Since instance variables have nothing to do with inheritance, it follows that an instance variable used by a subclass cannot “shadow” an instance variable in the super-class. If a subclass uses an instance variable with the same name as a variable used by one of its ancestors, it will overwrite the value of its ancestor’s variable.


How to Use Polymorphism to Make a Better Activity Feed in Rails

How to Use Polymorphism to Make a Better Activity Feed in Rails

You won’t find “polymorphic partials” in Rails’ API documentation. However, the general programming technique of polymorphism can be applied to Rails partials.

Example: an activity feed for an eBay marketplace

Ruby on Rails LogoImagine you are signed into an application similar to eBay. You can buy or sell items on the marketplace. In order to buy an item, you need to bid on it. You see an activity feed that includes bids, comments, and other things that are relevant to you.


We’ll use a polymorphic association:

class Activity < ActiveRecord::Base
  belongs_to :subject, polymorphic: true
  belongs_to :user

When subjects like Bids and Comments are created, we’ll create Activity records that both the seller and bidder will see in their activity feeds.

class Bid < ActiveRecord::Base
  belongs_to :item
  belongs_to :user

  after_create :create_activities

  def bidder

  def seller


  def create_activities

  def create_activity_for_bidder
      subject: self,
      name: 'bid_offered',
      direction: 'from',
      user: bidder

  def create_activity_for_seller
      subject: self,
      name: 'bid_offered',
      direction: 'to',
      user: seller

In a production app, we’d create those records in a background job. We’ve simplified here for example’s sake. The further benefit of creating them in the background can be seen when we create activities for each of the commenters, which may be a large number for an active marketplace item:

class Comment < ActiveRecord::Base
  belongs_to :item
  belongs_to :user

  after_create :create_activities

  def seller


  def create_activities
    (commenters_on_item + [seller]).uniq.each do |user|
        subject: self,
        name: 'comment_posted',
        direction: 'to',
        user: user

  def commenters_on_item

Now that we have a clean set of activities in a database table, the SQL lookup is simple:

class User < ActiveRecord::Base
  has_many :activities

  def recent_activities(limit)
    activities.order('created_at DESC').limit(limit)

This is the core benefit of structuring our data this way. At runtime, we find the data via a single indexable foreign key, user_id:

create_table :activities, do |t|
  t.timestamps null: false
  t.integer :subject_id, null: false
  t.string :subject_type, null: false
  t.string :name, null: false
  t.string: direction, null: false
  t.integer: user_id, null: false

add_index :activities, :subject_id
add_index :activities, :subject_type
add_index :activities, :user_id


We’ve seen alternative implementations that look something like this:

class User < ActiveRecord::Base
  def recent_activities(limit)
    [comments,, bids].

There are a couple of problems with that approach:

  • the number of ActiveRecord objects loaded into memory is large
  • sorting is done in Ruby, which is slower than SQL


We make our fast lookup:

@activities = current_user.recent_activities(20)

Polymorphic Rails partials

Now, let’s show the activity feed in a view:

  - @activities.each do |activity|
      = render "#{}_#{activity.direction}_current_user", subject: activity.subject

Here we render partials with polymorphism. Through the single "#{}_#{activity.direction}_current_user" interface, we’re able to render multiple partials:

  • bid_offered_to_current_user
  • bid_offered_from_current_user
  • comment_posted_to_current_user

When we write upcoming features, we’ll be able to render even more partials representing many other interactions, using the same simple structure:

  • bid_accepted_from_current_user
  • bid_rejected_to_current_user
  • etc.

In turn, each partial is small, contains no conditional logic, and results in copy text that makes sense for the user’s context:

The Old Man offered a bid of $100 for your Red Ryder BB gun with a compass in the stock, and this thing which tells time.

We can style each partial differently, perhaps showing an image of the items being offered or the avatars of the users who commented.

Nowhere do we do anything like this:

  - @activities.each do |activity|
      - if activity.subject_type == 'Bid' && activity.direction == 'to'
        = render "bid_offered_to_current_user", subject: activity.subject
      - elsif
        = # ...

We’ve replaced an ugly conditional with polymorphism and used a couple of naming conventions to made it easier to add subject types without changing the view logic.



Split is Not Enough: Unicode Whitespace for Rubyists

Split is Not Enough: Unicode Whitespace for Rubyists

That code is legal Ruby! If you ran it, you’d see 8. How? There’s a tale to tell..

The String with the Golden Space

I was on IRC in #nwrug enjoying festive cheer with fellow Northern Rubyists when ysr23 presented a curious problem.

He was using a Twitter library that returned a tweet, "@twellyme film", in a string called reply. The problem was that despite calling reply.split, the string refused to split on whitespace. Yet if he did "@twellyme film".split in IRB, that was fine.

International man of mystery Will Jessop suggested checking $; (it’s a special global variable that defines the default separator for String#split). It was OK.

In an attempt to look smarter than I am, I suggested reply.method(:split).source_location to see if the String class had been monkey-patched by something annoying. Nope. (Though this is a handy trick if you do want to detect if anyone’s tampered with something.)

Someone suggested Mr. Ysr23 show us reply.codepoints.to_a:

# reply.codepoints.to_a
 => [64, 116, 119, 101, 108, 108, 121, 109, 101, 160, 102, 105, 108, 109]

Something leapt out at me. Where was good old 32!? Instead of trusty old ASCII 32 (space) stood 160, a number alien to my ASCII-trained 1980s-model brain.

From Google with Love

To the Google-copter!

Aha! Non-breaking space. That’s why split was being as useful as a chocolate teapot.

After an intense 23 seconds of discussion, we settled on a temporary solution for Mr. Ysr23 who, by this time, was busy cursing Twitter and all who sailed upon her:

reply.gsub(/[[:space:]]/, ' ').split

The solution is simple. Use the the Unicode character class [[:space:]] to match Unicode’s idea of what whitespace is and convert all matches into vanilla ASCII whitespace. reply.split(/[[:space:]]+/) is another more direct option – we just didn’t think of it at the time.

Quantum of Spaces

Solving an interesting but trivial issue wasn’t where I wanted to end my day. I’d re-discovered an insidious piece of Unicode chicanery and was in the mood for shenanigans!

Further Googling taught me you can type non-breaking spaces directly on OS X with Option+Space. (You can do the homework for your own platform.)

I also knew Ruby 1.9 and beyond would let you use Unicode characters as identifiers if you let Ruby know about the source’s encoding with a magic comment, so it was time for shenanigans to begin!

My first experiment was to try and use non-breaking spaces in variable names.

Cool! So what about variable names and method names?

What about without any regular printable characters in the identifiers at all?

And so we’re back to where we started. A hideous outcome from a trivial weekend on IRC. But fun, nonetheless. Stick it in your “wow, nice, but totally useless” brain box.

A Warning

Please don’t use this in production code or the Ruby gods will come and haunt you in your sleep. But.. if you want to throw some non-breaking spaces into your next pair programming session, conference talk, or job interview, just to see if anyone’s paying attention, I’ll be laughing with you. (And if you’re a C# developer too, Andy Pike tells me that C# supports these shenanigans too.)

Ruby on Rails Fundamentals


Ruby on Rails Fundamentals

Ruby on Rails Fundamentals

Ruby on Rails Fundamentals

These days, experience with web technologies is more in demand than ever—but Ruby on Rails is outpacing the rest. Twitter was built with Ruby on Rails, and Rails has also become the go-to framework for hot startups.

Ruby on Rails is a young, lean framework focused on developer productivity and happiness. The chief reason for Rails’s growing popularity is the ability to rapidly build, enhance, and scale websites and web services thanks to its cutting-edge design, human-readable syntax, and open ethos of sharing your ideas with others. Working in Rails makes you part of a larger community of forward-thinking programmers advancing the vanguard of web technology.

Mastering Ruby on Rails actually entails learning two different pieces: the Rails framework itself, and the Ruby programming language underpinning it. Like Rails, the Ruby language is designed with the needs of the programmer, not the computer, in mind, making it fast and fun to write powerful code Read More…

For more details visit Training-NYC or enroll Ruby on Rails Fundamentals class here.