Skip to content

Instantly share code, notes, and snippets.

@oivoodoo
Created September 24, 2012 06:36
Show Gist options
  • Select an option

  • Save oivoodoo/3774620 to your computer and use it in GitHub Desktop.

Select an option

Save oivoodoo/3774620 to your computer and use it in GitHub Desktop.
Return default value if you have nil value for the column
module Extensions
module DefaultAttributeValue
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def default_attribute_value(key, value)
self.class_eval %Q{
def #{key}
value = read_attribute(:#{key})
value || #{value}
end
}
end
end
end
end
require 'spec_helper'
class TestClass
include Extensions::DefaultAttributeValue
attr_accessor :key
default_attribute_value :key, 0
def read_attribute(key)
instance_variable_get("@#{key}")
end
end
describe Extensions::DefaultAttributeValue do
let(:object) { TestClass.new }
it { object.key.should == 0 }
context 'when key assigned' do
before { object.key = 1 }
it { object.key.should == 1 }
end
end
class Stat < ActiveRecord::Base
include Extensions::DefaultAttributeValue
default_attribute_value :clicks, 0
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment