1

I'm fairly sure that's a useless title... sorry.

I want to be able to pass in a Class to a method, and then use that class. Here's an easy, working, example:

def my_method(klass)
  klass.new
end

Using that:

>> my_method(Product)
=> #<Product id:nil, created_at: nil, updated_at: nil, price: nil>
>> my_method(Order)
=> #<Order id:nil, created_at: nil, updated_at: nil, total_value: nil>

What doesn't work is trying to use the klass variable on a module:

>> ShopifyAPI::klass.first
=> NoMethodError: undefined method `klass' for ShopifyAPI:Module

Am I attempting an impossible task? Can anyone shed some light on this?

Cheers

4

2 回答 2

3

首先,我不认为这是不可能的。

当然,没有klass为模块定义方法<-这是真的,因为ShopifyAPI.methods.include? "klass" # => false

但是,类是模块中的常量。模块有一个constants方法可以用来检索类。这个方法的问题是它也在模块中检索不是类的常量。

我为您的问题想出了这个解决方法

# get all the classes in the module
klasses = ShopifyAPI.constants.select do |klass|
    ShopifyAPI.const_get(klass).class == Class
end

# get the first class in that list
klasses.first
于 2011-07-28T09:25:19.317 回答
0

你也可以使用 module_eval:

ShopifyAPI.module_eval {klass}.first

希望我的问题是正确的:)

irb(main):001:0> module ShopifyAPI
irb(main):002:1> class Something
irb(main):003:2> end
irb(main):004:1> end
=> nil
irb(main):005:0> klass = ShopifyAPI::Something
=> ShopifyAPI::Something
irb(main):006:0> ShopifyAPI::klass
NoMethodError: undefined method `klass' for ShopifyAPI:Module
        from (irb):6
        from C:/Ruby192/bin/irb:12:in `<main>
irb(main):007:0> ShopifyAPI.module_eval {klass}
=> ShopifyAPI::Something
irb(main):008:0>
于 2011-07-28T09:41:48.933 回答