Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@pedroteixeira
Created August 29, 2012 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedroteixeira/3515871 to your computer and use it in GitHub Desktop.
Save pedroteixeira/3515871 to your computer and use it in GitHub Desktop.
dynamic date+time acessors a datetime attribute in rails model
# and you can handle formating in your controller
def action
params[:start_at] = params[:start_at_date] + ' ' + params[:start_at_time]
params.delete :start_at_date
params.delete :start_at_time
end
class Form
class << self
def add_acessors(obj, *attrs)
attrs.each do |attr|
obj.instance_eval "class << self; attr_accessor \"#{attr.to_s}\"; end;"
end
end
def split_date_time(obj, attr)
attr = attr.to_s
date_attr = attr + '_date'
time_attr = attr + '_time'
add_acessors obj, date_attr, time_attr
value = obj.send(attr)
if value.respond_to?(:strftime)
obj.send date_attr +'=', value.strftime('%d/%m/%Y')
obj.send time_attr +'=', value.strftime('%H:%M')
end
end
end
end
- Form.split_date_time resource, :start_at
= f.input :start_at_date, :as => :date_picker
= f.input :start_at_time, :as => :time_text
@pedroteixeira
Copy link
Author

Sick of writing accessors and poluting yout model class?

@pedroteixeira
Copy link
Author

oh, it is a big shame to use model for form binding (i.e. no command or dto) -> that's the rails way :p

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