Reputation: 2435
I have a method defined in application_helper.rb:
def bayarea_cities
[
['San Francisco', 'San Francisco'],
['Berkeley', 'Berkeley'],
...
]
end
I'm also using Grape to create an API. It's in its own module outside the Rails app:
module FFREST
class API_V2 < Grape::API
...
I'm pretty sure Grape is a Rack app, so it doesn't have normal access to the Rails modules. When I try to call the 'bayarea_cities' method in one of the API methods, I get an undefined variable or method error. I've tried include the ApplicationHelper module with 'include ApplicationHelper', but this did not work.
How can I get access to this inside the API class?
UPDATE:
Thanks for the update Deefour. I added extend self
to my Helpers module, and referenced the methods as instance/mixin methods (not as module methods), but I'm still getting the same error. In my lib/helpers.rb file I have:
module Helpers
extend self
def bayarea_cities
[
'San Francisco',
'Berkeley',
'Danville',
'Oakland',
'Daly City',
'Sunnyvale'
]
end
def us_states
['CA']
end
end
and in my API file I have:
module FFREST
class API_V1 < Grape::API
include Helpers
version 'v1', :using => :header, :vendor => 'feedingforward'
...
And of course, I have the config/initializers/helpers.rb file that says require "helpers"
But when I call the US states API method, for instance, by going to http://localhost:5000/api/states
, I get:
undefined local variable or method `us_states' for #<Grape::Endpoint:0x007fd9d1ccf008>
Any ideas?
Upvotes: 0
Views: 3284
Reputation: 35360
lib/helpers.rb
file with the contents: module Helpers; end
bayarea_cities
method into this module definitionconfig/initializers/helpers.rb
file containing require "helpers"
ApplicationHelpers
class, add include Helpers
API_V2
class add include Helpers
You'll now have told Rails to make the Helpers
module available within your application, and made bayarea_cities
available as a method within both your Grape API class and your Rails app. The above are steps simply to get the point across - you need to put this common functionality in a place it can be easily accessed by any part of your application. You can (and should) use namespace your Helpers
module.
Another tip: add extend self
to the module to avoid the need to define everything as class methods as you mentioned in the comment
module Helpers
extend self
def bayarea_cities
#...
end
end
Finally, if you're including the module properly with include Helpers
, you should be able to acces the method simply as bayarea_cities
, not Helpers.bayarea_cities
. If this isn't the case, you should definitely show the error you get so we can sort that out for you.
Upvotes: 3