简体   繁体   中英

Accessing gem class methods in rails app

I have created my own gem 'mygem'. In the lib directory I have mygem.rb ruby file. This file has 3 methods defined.

Now I have created a rails app and I intend to use my gem in this app. In the controller ruby file I want to create a object and use the methods of my gem. But it is giving me error.

Here is the code of my controller ruby file:-

class StaticPagesController < ApplicationController
  obj= Newgem.new()    

  def home
    @message1 = obj.head
    @message2 = obj.paraone
    @message3 = obj.paratwo
  end  
end 

local variables (ones without an @ sign) will not carry through from the class scope to inside a method. It's not clear to me what you are trying to do, but you could perhaps do it in a before_filter, like so:

class StaticPagesController < ApplicationController
  before_filter :create_newgem

  def home
    @message1 = @obj.head
    @message2 = @obj.paraone
    @message3 = @obj.paratwo
  end  

protected
  def create_newgem
    @obj = Newgem.new()  
  end
end 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM