Skip to content

Instantly share code, notes, and snippets.

@sj26
Created December 15, 2011 01:49
Show Gist options
  • Save sj26/1479457 to your computer and use it in GitHub Desktop.
Save sj26/1479457 to your computer and use it in GitHub Desktop.
Handle natural-language duration inputs with ChronicDuration.
= semantic_form_for @my_model do |f|
= f.inputs do
= f.input :interval_duration
= f.buttons
module DurationConversion
extend ActiveSupport::Concern
included do
attribute_method_suffix "_duration"
attribute_method_suffix "_duration="
end
# Handle *_duration for method_missing.
def attribute_duration(attribute_name)
ChronicDuration.output(send(attribute_name), :format => :long)
end
# Handle *_duration= for method_missing.
def attribute_duration=(attribute_name, value)
send(:"#{attribute_name}=", ChronicDuration.parse(value))
end
end
class MyModel < ActiveRecord::Base
include DurationConversion
# t.integer :interval
end
@sj26
Copy link
Author

sj26 commented Dec 15, 2011

Only problem is preserving potentially-incorrect user input between posts and validating... don't want to overcomplicate so discarding unparsable values at present.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment