user1618840
user1618840

Reputation: 453

gem namespaces within rails class

I'm brand new to rails (and ruby) and having a a lot of trouble with accessing different namespaces. Specifically, I can't access the namespace of the flickraw gem from within a controller class:

class ImageSourcesController < ApplicationController
    def show
        list   = flickr.photos.getRecent
        ...
    end
end

Calling this method, I get the response:

undefined local variable or method `flickr' for #<ImageSourcesController:0x00000005006658>

I am using bundler, which I thought ensured that the methods of all gems in the gemfile are required by rails.

EDIT: I'm stupid, turns out I just needed to reset the server!

Upvotes: 0

Views: 936

Answers (1)

max
max

Reputation: 101811

It is a good idea to create an initializer for flickraw:

# config/initializers/flickraw.rb
FlickRaw.api_key= ENV['FLICKR_API_KEY']
FlickRaw.shared_secret= ENV['FLICKR_API_SECRET']

If you are creating a open source app you may want to use ENV variables to store your API key and shared secret. The dotenv gem is a really nice tool for that.

You also seem to be confused about namespaces in Ruby. Ruby doesn't actually have namespaces in the same way as for example PHP which has a special keyword and namespace accessors.

Ruby has modules which act as both namespaces (grouping classes, constants etc.) and traits. Foo::Bar.create() is an example of accessing a class method on a "namespaced" class.

module Foo
  class Bar
    def create
    end
  end
end

Your flickraw example is simply accessing nested properties (which does'nt really have anything to do with namespaces):

 flickr.photos.getRecent

Your taking the object flickr (which flickraw creates when we require flickraw) and sending it the message photos which returns a FlickRaw::Flickr::Photos instance.

We then send the message getRecent to flickr.photos

Upvotes: 1

Related Questions