开发者

ROR + Access Constant in Controller and Define in Config/initializer/constant.rb

Here in my project I want to use constant in place of simple 开发者_开发技巧string. For this, I have define color constant in config/initiailizer/constant.rb file. Here is the code ::

RED = "red"
GREEN = "green"
STALE = "stale"
YELLOW = "yellow"

Now I want to access this constant in one of my controller so, how can access this. I tried a lot to search something at Google but could not get any success. Please have a look.


If you're using Rails 3, you can store constants in your constant.rb file like this:

AppName::Application.config.YELLOW = "yellow"

And access them from everywhere (controllers, models, etc) the same way:

AppName::Application.config.YELLOW

And if you need to store some environment-specific constants, you can create a YML-file in config/config.yml with contents like:

development:
  yellow: "yellow"

production:
  yellow: "green"

and replace your YELLOW constant with this:

AppName::Application.config.COLOR = YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env]

and access your environment-specific COLOR constant like this:

AppName::Application.config.COLOR[:yellow]


If you're literally just storing constants that point to strings of the same name, you should really just be using symbols. They are better on memory, and you aren't forcing this awkward pseudo-enterprise requirement into Rails.

So rather than using something like this:

class MyController < ApplicationController
  def show
    @background_color = ::GREEN
  end
end

You could use a symbol:

class MyController < ApplicationController
  def show
    @background_color = :green
  end
end

Also, if you insist on defining a bunch of related color-constants, you should really avoid polluting the global scope with them and instead encase them in a module:

module Colors
  GREEN = 'green'
  BLUE = 'blue'
  ...
end

And then access them (from within another class/module defined inside another [such as a controller]):

puts "I'm #{::Colors::BLUE}, like him, inside and outside."

Or if you'll be using them in another class/module frequently:

class Eiffel65
  include ::Colors

  def house_color
    BLUE
  end
end

Make sense?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜