Easily store hard coded values with Active Hash

Hard coded data is usually stored in the class that uses it.

#app/models/camper.rb
class Camper
  MEALS = {1: 'breakfast', 2:'lunch', 3: 'supper'}
 
end
 
Camper::MEALS

Active Hash is a library that helps Rails projects abstract this data out into an ActiveRecord like model:

#app/models/meals.rb
class Meals < ActiveHash::Base
  belongs_to :camper
 
  self.data = [
    { id: 1, name: 'breakfast'},
    { id: 2, name: 'lunch'},
    { id: 3, name: 'supper'}
  ]
end
 
#app/models/camper.rb
class Camper
  # required for ActiveRecord 3.1 or later
  extend ActiveHash::Associations::ActiveRecordExtensions
  has_many :meals
 
end
 
Camper.meals

This benefits our classes by removing data it’s not meant to represent. It helps the code architecture by not littering the application with constants. If someday we want that data to be an ActiveRecord model the code is already organized for it.

ActiveHash also works with FactoryGirl

FactoryGirl.define do
  factory :camper do
    name { 'Sally' }
    meals
  end
end

Leave a Reply

Your email address will not be published. Required fields are marked *