Created
July 6, 2012 15:22
-
-
Save ordinaryzelig/3060849 to your computer and use it in GitHub Desktop.
Include Rails-style initialize method in a class
This file contains 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
.rvmrc | |
Gemfile | |
Gemfile.lock |
This file contains 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
Gem::Specification.new do |s| | |
s.name = 'rails_style_initializer' | |
s.version = '0.0.1' | |
s.platform = Gem::Platform::RUBY | |
s.author = 'Jared Ning' | |
s.email = '[email protected]' | |
s.summary = 'Rails-style initializer' | |
s.description = 'Include Rails-style initialize method in a class. It also includes #attributes=.' | |
s.files = ['rails_style_initializer.rb'] | |
s.test_file = 'rails_style_initializer.spec.rb' | |
s.require_path = '.' | |
end |
This file contains 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 RailsStyleInitializer | |
def initialize(atts = {}) | |
self.attributes = atts | |
end | |
def attributes=(atts) | |
atts.each do |att, value| | |
send "#{att}=", value | |
end | |
end | |
end |
This file contains 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 'minitest/autorun' | |
require 'rails_style_initializer' | |
class Player | |
include RailsStyleInitializer | |
attr_accessor :name | |
attr_accessor :score | |
def initialize(attributes = {}) | |
super | |
@score ||= 0 | |
end | |
end | |
describe Player do | |
it 'is initialized with attributes' do | |
player = Player.new(name: 'Roger Federer', score: 40) | |
player.name.must_equal 'Roger Federer' | |
player.score.must_equal 40 | |
end | |
it 'can be initialized with nothing' do | |
player = Player.new | |
player.name.must_be_nil | |
end | |
it 'allows defaults when implemented' do | |
player = Player.new | |
player.score.must_equal 0 | |
end | |
it '#attributes= assigns attributes' do | |
player = Player.new | |
player.attributes = {name: 'Andy Murray', score: 30} | |
player.name.must_equal 'Andy Murray' | |
player.score.must_equal 30 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment