【问题标题】:How to use a dynamically chosen class in a module如何在模块中使用动态选择的类
【发布时间】:2011-07-28 08:58:29
【问题描述】:

我很确定这是个没用的标题……抱歉。

我希望能够将一个类传递给一个方法,然后使用该类。这是一个简单、有效的示例:

def my_method(klass)
  klass.new
end

使用它:

>> 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>

不起作用的工作是尝试在模块上使用klass 变量:

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

我在尝试一项不可能完成的任务吗?任何人都可以对此有所了解吗?

干杯

【问题讨论】:

  • 为什么你认为你正在使用的类上应该有一个klass方法?你想达到什么目的?
  • @obrok 我不认为应该有一个类方法,我希望类变量被替换到模块中,这样ShopifyAPI::klassShopifyAPI::Productklass == Productklass == Order时是ShopifyAPI::Order

标签: ruby-on-rails ruby shopify


【解决方案1】:

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

当然,没有为模块定义 klass 方法 ShopifyAPI.methods.include? "klass" # => false

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

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

# 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

【讨论】:

  • 您的回答让我找到了我正在寻找的解决方案!我想要的是ShopifyAPI.const_get(klass.to_s),而klass 可以是ProductOrder 等。不太确定您的解决方案本身应该做什么,因为获取ShopifyAPI 模块的类名字符串数组并没有太大帮助。我需要类本身,所以我可以调用它的方法。但还是要感谢!
  • 我的解决方案中的块返回数组["Product", "Order"] 假设ProductOrderShopifyAPI 模块中指定的类。在选择第一个之前,我从函数外部获取模块中的所有类(:您的解决方案更加简洁和精确
【解决方案2】:

你也可以使用 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2011-03-22
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 2020-10-29
    相关资源
    最近更新 更多