Skip to content

Commit

Permalink
some integration work with form-helpers
Browse files Browse the repository at this point in the history
apparently, form.checkbox :foo wants form.object.foo to return 0 or 1 to determine "checked"-state. the return-value of foo? is not taken into account.
  • Loading branch information
kronn committed Jun 5, 2011
1 parent aa09e00 commit 233a8d6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
22 changes: 15 additions & 7 deletions lib/date_checkbox/has_date_checkbox.rb
Expand Up @@ -6,26 +6,34 @@ def self.included(base)

module ClassMethods
def has_date_checkbox(db_field)
method_name = db_field.to_s.sub(/_at$/, '')
# if db_field.to_s =~ /_at$/ #&& has_attribute?(db_field)
column_name = db_field
method_name = db_field.to_s.sub(/_at$/, '')
# elsif has_attribute?(:"#{db_field}_at")
# else
# column_name = :"#{db_field}_at"
# method_name = db_field.to_s
# end

# send :include, InstanceMethods
class_eval do
define_method("#{method_name}") do
if attribute_present?(db_field)
I18n.t(:"is_#{method_name}")
if attribute_present?(column_name)
"1" # I18n.t(:"is_#{method_name}")
else
I18n.t(:"not_#{method_name}")
"0" # I18n.t(:"not_#{method_name}")
end
end

define_method("#{method_name}?") do
attribute_present?(db_field)
attribute_present?(column_name)
end

define_method("#{method_name}=") do |value|
if value.to_s == "0"
write_attribute(db_field, nil)
write_attribute(column_name, nil)
else
write_attribute(db_field, Time.now)
write_attribute(column_name, Time.now)
end
end
end
Expand Down
6 changes: 4 additions & 2 deletions test/has_date_checkbox_test.rb
Expand Up @@ -19,13 +19,15 @@ def teardown
test "returns something falsish when attribute is not set" do
instance.published_at = nil
assert_equal false, instance.published?
assert_equal I18n.t(:not_published), instance.published
assert_equal '0', instance.published
# assert_equal I18n.t(:not_published), instance.published
end

test "returns something trueish when attribute is set" do
instance.published_at = 1.minute.ago
assert_equal true, instance.published?
assert_equal I18n.t(:is_published), instance.published
assert_equal '1', instance.published
# assert_equal I18n.t(:is_published), instance.published
end

test "has_date_checkbox defines a custom writer for the given attribute" do
Expand Down

0 comments on commit 233a8d6

Please sign in to comment.