kotp
9/21/2011 - 6:26 PM

Bang!

Bang!

require File.expand_path('bang')

class ObjectWithBang
  extend Bang
end

describe Bang do

  let(:object) do
    object = ObjectWithBang.new
    object.stub(:attribute).and_return(1)
    object.stub(:get_attribute).and_return(2)
    object
  end

  context 'with one banged attribute' do

    before { ObjectWithBang.send(:bang, :attribute) }

    it 'should save the attribute value' do
      object.should_receive(:update_attribute).with(:attribute, 1)
      object.attribute!
    end

  end

  context 'when the attribute and method names differ' do

    before { ObjectWithBang.send(:bang, :get_attribute => :attribute) }

    it 'should save the attribute value' do
      object.should_receive(:update_attribute).with(:attribute, 2)
      object.get_attribute!
    end

  end

end

module Bang

  def bang(attributes)

    [*attributes].each do |attribute|
      key, value = attribute
      define_method("#{key}!") { update_attribute(value || key, send(key)) }
    end

  end

end

Gem::Specification.new do |s|
  s.name        = 'bang'
  s.version     = '0.1.0'
  s.platform    = Gem::Platform::RUBY
  s.author      = 'Jeff Kreeftmeijer'
  s.email       = 'jeff@kreeftmeijer.nl'
  s.summary     = 'Bang!'
  s.description = 'Bangs existing model methods'

  s.files         = ['bang.rb']
  s.test_file     = 'bang_spec.rb'
  s.require_path  = '.'

  s.add_development_dependency('rspec', ["~> 2.0"])
end