Created
September 24, 2012 06:36
-
-
Save oivoodoo/3774620 to your computer and use it in GitHub Desktop.
Return default value if you have nil value for the column
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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