I tried to put up a Ruby Gem based on Railscast Episode 033 Making a Plugin. I got the gem created and uploaded to Rubygems.org as stringify-time
, but the setter method is not working.
The main part of the gem
module StringifyTime
def stringify_time(*names)
names.each do |name|
define_method "#{name}_string" do
read_attribute(name).to_s(:db) unless read_attribute(name).nil?
end
define_method "#{name}_string=" do |time_str|
begin
write_attribute("#{name}", Time.zone.parse(time_str))
rescue ArgumentError
instance_variable_set("@#{name}_invalid", true)
end
end
define_method "#{name}_invalid?" do
instance_variable_get("@#{name}_invalid")
end
end
end
end
ActiveRecord::Base.send(:extend, StringifyTime)
A attribute symbol is passed in and getter and setter methods are created. The getter method works, but when I try to update the attribute through the form, the data is not saved.
using the stringify_time
method in the Task model
class Task < ActiveRecord::Base
validates_presence_of :name
stringify_time :due_at
# def due_at_string
# due_at.to_s(:db)
# end
# def due_at_string=(due_at_str)
# self.due_at = Time.parse(due_at_str)
# rescue ArgumentError
# @due_at_invalid = true
# end
def validate
errors.add :due_at, 'is invalid' if due_at_invalid? # @due_at_invalid
end
end
When I uncomment the setter method I wrote manually, then I can edit the attribute.