mercredi 7 mars 2018

rails string substitution or similar solution in controller

I'm building a site with users in all 50 states. We need to display information for each user that is specific to their situation, e.g., the number of events they completed in that state. Each state's view (a partial) displays state-specific information and, therefore, relies upon state-specific calculations in a state-specific model. We'd like to do something similar to this:

@#{user.state} = #{user.state.capitalize}.new(current_user)

in the users_controller instead of

@illinois = Illinois.new(current_user) if (@user.state == 'illinois')
.... [and the remaining 49 states]
@wisconsin = Wisconsin.new(current_user) if (@user.state == 'wisconsin')

to trigger the Illinois.rb model and, in turn, drive the view defined in the users_controller by

def user_state_view
  @user = current_user
  @events = Event.all
  @illinois = Illinois.new(current_user) if (@user.state == 'illinois')
end

I'm struggling to find a better way to do this / refactor it. Thanks!

Aucun commentaire:

Enregistrer un commentaire