Created
August 29, 2012 17:26
-
-
Save pedroteixeira/3515871 to your computer and use it in GitHub Desktop.
dynamic date+time acessors a datetime attribute in rails model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- Form.split_date_time resource, :start_at | |
= f.input :start_at_date, :as => :date_picker | |
= f.input :start_at_time, :as => :time_text |
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
Sick of writing accessors and poluting yout model class?