Tag: 内省

Ruby on Rails:如何检查多重和单一forms的名称

我用命令创建了一个模型Anonymous rails g model Anonymous section_id:integer aid:string fake:bool active:bool 但迁移中的表名称称为匿名 class CreateAnonymous < ActiveRecord::Migration def change create_table :anonymous do |t| t.integer :section_id t.string :aid t.bool :fake t.bool :active t.timestamps end end end 我是对的,Anonymous的复数forms也是Anomymous吗? (英语不是我的母语)。 我如何才能看到Rails为我的模型提供的复数名称? 像rake routes ?

define_method带有预定义的关键字参数

我想定义一个采用关键字参数的方法。 我希望在没有提供关键字参数时提出,我可以自己编写代码 – 但理想情况下我想让Ruby为我做这些。 此外,我希望能够使用Method#parameters检查新定义的方法。 如果我使用速记双拼(如**kwargs ),我期望的实际结构对parameters不可见。 我当然可以这样做: define_method(:foo) do | foo:, bar: | # … end 达到了预期的效果: method(:foo).parameters # => [[:keyreq, :foo], [:keyreq, :bar]] 但我不能以编程方式传递这些参数,它们必须放在代码中。 有没有办法绕过这个?

我如何检查Ruby对象的方法?

我想知道是否有一个Ruby方法调用只显示它调用的Ruby对象定义的方法,而不是它的祖先类定义的所有方法,这是methods似乎做的。

比较Procs的内容,而不是结果

使用Ruby 1.9.2 问题 比较两个过程的内容,而不是结果。 我知道结果因为停止问题而无法测试但是没关系; 我还是不想测试结果。 例如 proc {@x == “x”} == proc {@x == “x”} => false # doh! 返回false,因为procs中的对象不一样。 我笨重的解决方案 我有一个解决方案,有点像我做我想要的但它并没有真正测试proc与我放入它的“相同”。 在我的特定情况下,我的procs的格式将始终是对实例变量的布尔测试,如下所示: {@x == “x” && @y != “y” || @z == String} 我编写了一个动态构建类的方法,并创建了设置为指定值的实例变量: def create_proc_tester(property_value_hash) new_class = Class.new.new new_class.class.class_eval do define_method(:xql?) { |&block| instance_eval &block } end property_value_hash.each do |key, value| new_class.instance_variable_set(“@#{key}”, […]

Ruby方法拦截

我想拦截ruby-class上的方法调用,并且能够在实际执行方法之前和之后执行某些操作。 我尝试了以下代码,但得到错误: MethodInterception.rb:16:in before_filter’: (eval):2:in alias_method’:undefined method say_hello’ for class HomeWork’(NameError)from(eval):2:in`after_filter’ 任何人都可以帮我做对吗? class MethodInterception def self.before_filter(method) puts “before filter called” method = method.to_s eval_string = ” alias_method :old_#{method}, :#{method} def #{method}(*args) puts ‘going to call former method’ old_#{method}(*args) puts ‘former method called’ end ” puts “going to call #{eval_string}” eval(eval_string) puts “return” end end class […]

Ruby String#to_class

从上一篇文章中做了一些修改以回应sepp2k关于命名空间的评论,我已经实现了String#to_class方法。 我在这里分享代码,我相信它可能会被重构,特别是“i”计数器。 您的意见表示赞赏。 class String def to_class chain = self.split “::” i=0 res = chain.inject(Module) do |ans,obj| break if ans.nil? i+=1 klass = ans.const_get(obj) # Make sure the current obj is a valid class # Or it’s a module but not the last element, # as the last element should be a class klass.is_a?(Class) || […]