0

Hi I am working on a Ruby on Rails project with ruby-2.5.0 and rails 5. I have written an api to check if certain words exist in a hash as follows:-

parser_controller.rb
# frozen_string_literal: true

class ParserController < ApplicationController
  def create
      search_words = ["Walmart","Optical","Anker"]
      if search_words.select{|w| parser_params.to_s.include?(w) }
        render json: {}, status: 200
      else
        render json: {}, status: 404
      end
    rescue StandardError
    render json: {}, status: 500
  end

  private

  def parser_params
    params.require(:data)
          .permit!
          .transform_keys(&:underscore)
  end
end

I want to know where should i place this array search_words = ["Walmart","Optical","Anker"] as its size can be increase. Please help me. Thanks in adavance.

awsm sid
  • 595
  • 11
  • 28

2 Answers2

2

if search_words only used in ParserController, set it to constant SEARCH_WORDS

class ParserController < ApplicationController
  SEARCH_WORDS = ["Walmart","Optical","Anker"]
  def create
      if SEARCH_WORDS.select{|w| parser_params.to_s.include?(w) }
        render json: {}, status: 200
      else
        render json: {}, status: 404
      end
    ...
  end
end

If search_words used in more than one controller, set constant SEARCH_WORDS in ApplicationController

If search_words used in anywhere(models/helpers/custom class/...), set constant in application.rb or config/initializers/global_constant.rb

If search_words are frequently increased or decreased, create model(db tables) to store them.

王信凱
  • 453
  • 3
  • 9
  • Thanks search_words only used in ParserController. Is it the correct way to set it to constant SEARCH_WORDS in the same controller? – awsm sid Apr 01 '18 at 05:54
  • It is the correct way to set constant in any class, not just controller. learn more https://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/constants.html – 王信凱 Apr 02 '18 at 01:11
1

You can define a singleton class in lib folder as mentioned in the below mentioned link:

how do I create a singleton global object in rails

Or you can create a file in config/initializers where you define the array and use it anywhere you want in the application.

Rohan
  • 2,681
  • 1
  • 12
  • 18