Tintin81
Tintin81

Reputation: 10207

How to set constant dynamically in Ruby on Rails helper function?

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.

Upvotes: 2

Views: 1614

Answers (3)

Rails Guy
Rails Guy

Reputation: 3866

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.

Upvotes: 1

Sachin Singh
Sachin Singh

Reputation: 7225

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.

Upvotes: 2

barvaz
barvaz

Reputation: 641

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

Upvotes: 0

Related Questions