0

I want to be able to select a yaml file inside a folder called market. This folder will be in config/market. Inside this folder I will have many yaml files, for example:

  config/market
        usa.yml
        cad.yml
        eur.yml

Inside each yml file I will have same variables but different default values. for example on usa.yml

    ---
    :usa
      country: "United States"
      currency: "USD"

For eur.yml,

    ---
    :eur
     country: "European Union"
     currency: "EUR"

and so on. I want to use country and currency as global variables for example in my rails app. Depending on user location I will select the yaml file.

I want to select only one yaml file from the market folder when the user login in my application. Maybe do a before_action call in the application controller. Something like this

 before_action :set_market

 private
   def set_market
     if (statement)
      Config[:market] = :usa
     end
   end

How can I do this? Please any feedback will help.

aminhs
  • 45
  • 6

2 Answers2

0

You can use the YAML class to open the file. Look this link: https://ruby-doc.org/stdlib-2.1.3/libdoc/yaml/rdoc/YAML.html

Something like this:

CONFIG = YAML.load_file("#{Rails.root.to_s}/config/market/usa.yml")
CONFIG["usa"]

Hope this helps!

MarcusVinnicius
  • 240
  • 1
  • 7
0

Adding to the MarcusVinnicius' answer:

I would suggest using one yaml file with different market/zones. Let's assume you are using something like Spree for your market place which uses zones.

E.g.

1. Create a yaml file (settings.yml):

 production:
    united_kingdom:
      countries: ["GB", "IE"]
      currency: GBP
      //shipping ....
      //etc      
    united_states:
      countries: ["US", "PR"]
      currency:  USD
 development:
    united_kingdom:
      countries: ["GB", "IE", "test"]
      currency: GBP
      //shipping ....
      //etc      
    united_states:
      countries: ["US", "PR", "test"]
      currency:  USD

2. Load the yaml file

As in the previous answer, on a controller action.


-OR-

Do something similar to this

  1. Create the initializer config/initializers/load_config.rb with:

    CONFIG_PATH="#{Rails.root}/config/settings.yml"
    APP_CONFIG = YAML.load_file(CONFIG_PATH)[Rails.env]
    
  2. Use before_filter or after_sign_in/sign_up: link to do something like this:

    before_filter: set_market_spree_zone

    def set_market_spree_zone
        market = current_user.market 
        #or if you only have the user country do something like: get_zone_from_country(current_user.country)
        #convert to abrevation united_stated to us or vice-versa as needed
        @zone = APP_CONFIG['market']
        #then use @zone for Spree or whatever you need to set globally #in the APP
    
    end
    

(This could also be after_sign_in on device or overriding the create method of the session controller)

Let me know if that works.

sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40