Reputation: 153
How can I manipulate params in a more DSL way per country where each country has its own logic for province variable.
I would like to organise it better:
- create a configuration file per per each country.
- if files not exist than there will be a default file
- and each file is a ruby file that province parameter can be manipulated via ruby code which gives flexibility.
currently I do it in in the controller like this:
before_filter :modify_location_params, :only => [:create]
def location_params
params.require(:location).permit(
origin: [:name, :country, :city, :state, :postal_code, :address1, :address2,:province],
destination: [:name, :country, :city, :state, :postal_code, :address1, :address2,:province],
)
end
def modify_location_params
[:origin, :destination].each do |location|
unless (params[:location][location][:country].downcase =~ /(Sweden|sw)/).nil?
params[:location][location][:province] = 'SW'
end
unless (params[:location][location][:country].downcase == 'IL' && some_other_condition == true
params[:location][location][:city] = 'OM'
params[:location][location][:name] = 'some name'
end
end
end
Yes, I can do it in a switch/if statements but I think that since I have a lot of countries it would be a better way of doing a DSL like system for this manipulating. any ideas how implement such?
Upvotes: 0
Views: 104
Reputation: 1789
If I understand correctly you want to add different key-value pairs to a hash depending on the :country
value in that hash. If so then a YAML file should work.
Say you have the following in a YAML file
# country_details.yaml
sweden:
province: 'SW'
il:
city: 'OM'
name: 'some name'
Then you can define a method
def country_details(country)
parsed_yaml = YAML::load(File.open('path/to/file'))
details = parsed_yaml[country]
end
that you use like so
details = country_details('SW')
params[:location][location].merge! details
Upvotes: 0
Reputation: 665
Not totally sure I understand what you're trying to do, but if you just want different implementations of a similar method for each country you could make a class for each one and have them inherit from a parent country class. Something like
class Country
def as_origin
#default code
end
end
class Sweden < Country
def as_origin
#override default code here
end
end
There's also a bunch of good gems to help with country information if you want to avoid doing it all by hand
Upvotes: 1