Skip to content

Instantly share code, notes, and snippets.

@frankjmattia
Created October 30, 2013 02:50
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 frankjmattia/82a9945f30bde29eba88 to your computer and use it in GitHub Desktop.
Save frankjmattia/82a9945f30bde29eba88 to your computer and use it in GitHub Desktop.
Need to refactor but how?
# Want to take a DELEGATIONS hash like this:
#
# {
# object1: [ attribute11, attribute12 ],
# object2: [ attribute21, attribute22 ]
# }
#
# and turn it into a REVERSE_DELEGATIONS hash like this:
#
# {
# object1_attribute11: [ object1, attribute11 ],
# object1_attribute12: [ object1, attribute12 ],
# object2_attribute21: [ object2, attribute21 ],
# object2_attribute22: [ object2, attribute22 ]
# }
class RegistrationForm
DELEGATIONS = {
user: [
:first_name, :first_name=,
:last_name, :last_name=,
:email, :email=,
:password, :password=,
:password_confirmation, :password_confirmation=
],
organization: [
:name, :name=
]
}
REVERSE_DELEGATIONS = DELEGATIONS.inject({}) do |reverse_delegations, delegation|
klass = delegation.first
attrs = delegation.last
attrs.map { |attr| [ :"#{klass}_#{attr}", attr ] }.each do |lookup, attr|
reverse_delegations[lookup] = [ klass, attr ]
end
reverse_delegations
end
def self.human_attribute_name(method)
REVERSE_DELEGATIONS.has_key?(method) ? REVERSE_DELEGATIONS[method].first.to_s.camelize.constantize.send(:human_attribute_name, REVERSE_DELEGATIONS[method].last) : method.to_s.humanize
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment