2

I have this (simplified) helper function in Rails:

include Constants

def link_to_neighbour(direction, path)
  symbol = direction.upcase.constantize
  link_to symbol, path
end

In lib/constants I defined these constants:

PREVIOUS = "<<"
NEXT = ">>"

Yet when I use something like this in one of my views...

<%= link_to_neighbour('next', @user, user_path(@user)) %>

... I constantly get this error:

NameError
uninitialized constant NEXT

What am I missing here?

Thanks for any help.

3
  • 1
    I am not sure about the solultion to your problem, but why are you using so complicated solution just to print two chars? Isn't it better to go for translations maybe? Commented Jul 16, 2013 at 11:44
  • The problem occurs probably because your constants are namespaced, so you should refer them as Constants::PREVIOUS and Constants::NEXT. Commented Jul 16, 2013 at 11:50
  • I tried that already. I am using other constants in that same file too and never needed the Constants:: prefix there. Commented Jul 16, 2013 at 12:30

3 Answers 3

2

You can use const_missing hook of ruby.

def self.const_missing(name)
  const_set(name, some_value)
end

but the problem here seems that you have not loaded 'lib/constants.rb' file in application.rb of your application.

Put this line in your 'config/application.rb'

# Autoload lib/ folder including all subdirectories
config.autoload_paths += Dir["#{config.root}/lib/**/"]

If you don't want to put this line in your 'config/application.rb' then move constants.rb from lib to your 'config/initializers/' folder. Your Rails application loads each file there automatically.

Sign up to request clarification or add additional context in comments.

Comments

1

Your method should look like this:

def link_to_neighbour(direction, path)
  symbol = Object.const_get(direction.upcase)
  link_to symbol, path
end

Hope this will help.

Comments

0

I'd use a constants.yml

directions:
  PREVIOUS: "<<"
  NEXT: ">>"

this way I can use a tree of constants.

then in an initializer:

Constants = OpenStruct.new YAML.load_file(Rails.root.join('config/constants.yml')).with_indifferent_access

then in the helper method:

def link_to_neighbour(direction, path)
  symbol = Constants.directions[direction.upcase]
  link_to symbol, path
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.