ruby - Refactoring Rails controller code using the same string as a symbol, instance variable, and attribute -
i have following code in controller, , i'd know best way refactor 1 piece.
if @country if s.address s.address.country = @country else s.address = address.create(:country => @country) end end if @state if s.address s.address.state = @state else s.address = address.create(:state => @state) end end if @zip if s.address s.address.zip = @zip else s.address = address.create(:zip => @zip) end end
if there 1 variation here i'd like
[:country, :state, :zip].each |location| ... end
but in case i'm using :country, .country, , @country; what's better way take advantage of them having same 'root' string? thanks!
i recommend:
- following thin controller, fat model best practice , remove business logic controller.
- use meaningful variable names.
s
in example? if student - why not callstudent
?
assuming county
, state
text values , not associated fields change code following:
in controller:
student.create_or_update_address(county: @county, state: @state, zip: @zip)
in student.rb (or other model if s
not student)
def create_or_update_address(options) address_attributes = options.delete_if { |k, v| v.empty? } if address address.update_attributes(address_attributes) else s.address = address.create(address_attributes) end end
Comments
Post a Comment