开发者

Error Using Ruby generator in Rails (not Rails::Generator)

开发者 https://www.devze.com 2022-12-18 02:19 出处:网络
Edit: To be clear, I\'m trying to use this kind of generator (i.e. with a \'yield\' statement) not a Rails generator.

Edit: To be clear, I'm trying to use this kind of generator (i.e. with a 'yield' statement) not a Rails generator.

I have the following (simplified) initializer mixin in a Rails project that I could use some help with. What I wanted to do was create a generator to track Twitter API calls (this is just for debugging, I know about rate_limit_status).

require 'generator'
# Be sure to restart your server when you modify this file.
module TwitterMixin
  def get_auth
    @auth ||= Twitter::HTTPAuth.new(ENV['TWITTER_USER'], ENV['TWITTER_PASS'])
  end
  def count
    @counter ||= generator.new
    @counter.yield
  end
  def client
    p "#{count} Twitter API calls this iteration"
    @client ||= Twitter::Base.new(get_auth)
  end
end

The problem is that I'm getting the following error:

dlopen(/Users/john/.gem/ruby/1.8/gems/json-1.2.0/ext/json/ext/generator.bundle, 9): no suitable image found.  Did find:
/Users/john/.gem/ruby/1.8/gems/json-1.2.0/ext/json/ext/generator.bundle: mach-o, but wrong architecture - /Users/john/.gem/ruby/1.8/gems/json-1.2.0/ext/json/ext/generator.bundle

Which seems like a collision with the json generator, which is probably in a more开发者_运维问答 enclosing scope. The main question is how to I ensure a Ruby standard library class (specifically the generator class) is called?

I'm still new to Ruby, BTW, and searching for "generators in Rails" is pretty dominated by Rails::Generator, so this may be fairly obvious. Also, I'm open to more elegant solutions to this problem that I may have missed. Thanks.


Do you have a ruby gem on your system called "generator"? It sounds like ruby is having trouble locating the gem based on your require. If you're using the Rubigen generator, then you need:

require 'rubigen'

and so forth. try running:

gem list generator

If it doesn't pull anything up, you're probably calling the library by the wrong name.


You don't have to build a generator, you can use the yield method directly, which I didn't realize. This code works.

# Be sure to restart your server when you modify this file.
module TwitterMixin
  def get_auth
    @auth ||= Twitter::HTTPAuth.new(ENV['TWITTER_USER'], ENV['TWITTER_PASS'])
  end
  def count
    @num ||= 0
    while true
      num += 1
      yield num
    end
  end
  def client
    p "#{count} Twitter API calls this iteration"
    @client ||= Twitter::Base.new(get_auth)
  end
end


Let me reject my earlier answer and say that it was rather stupid of me to use "yield" thinking that it was a generator builtin similar to Python's yield statement. I learned today at our first RubyGorge meeting about Ruby blocks. Thus, I think I still seek a solution to this problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消