我有两种方法:
def ios_ids
@ios_ids ||= Array(GcmToken.find_by(users_id: "#{@event.user_id}", os_type: 'ios', alive: true).try(:reg_id))
end
def android_ids
@android_ids ||= Array(GcmToken.find_by(users_id: "#{@event.user_id}", os_type: 'android', alive: true).try(:reg_id))
end
我想将它们折射成类似下面的内容
%w(android ios).each do |os_type|
define_method(:"#{os_type}_ids") { "@#{os_type}_ids" ||= Array(GcmToken.find_by(users_id: "#{@event.user_id}", os_type: os_type, alive: true).try(:reg_id))}
end
但它不起作用
任何人都有任何答案或更好的解决方案吗?
答案 0 :(得分:8)
使用这种元编程非常严厉,特别是在操作像这样的实例变量时。通常情况下,当你沿着这条路走下去时,这是因为你有一个很多的情况需要整理。
让我们以较小的步骤解决这个问题:
def ios_ids
@ios_ids ||= Array(GcmToken.find_by(users_id: "#{@event.user_id}", os_type: 'ios', alive: true).try(:reg_id))
end
这里发生了一些非常奇怪的事情,比如"#{x}"
反模式,它引用了一个几乎总是毫无意义的值。如果您绝对需要字符串,请对相关值使用.to_s
。
这也会加载模型并尝试从中获取属性。那太浪费了。它还使用很少使用的不规则Array(...)
表示法将其打包。 [ ... ]
是首选。
所以清理一下你得到的东西:
def ios_ids
@ios_ids ||= GcmToken.where(
users_id: @event.user_id,
os_type: 'ios',
alive: true
).pluck(:reg_id)
end
将其归结为很多。现在它只是从reg_id
模型中获取所有关联的GcmToken
值。如果你有一个User has_many :gcm_tokens
和Event belongs_to :user
,这应该是这里的数据,那么你可以更清理它:
def ios_ids
@ios_ids ||= @event.user.gcm_tokens.where(
os_type: 'ios',
alive: true
).pluck(:reg_id)
end
您可以使用简单的scope
声明进行更多清理:
scope :alive_for_os_type, -> (os_type) {
where(os_type: os_type, alive: true)
}
然后它变得更小:
def ios_ids
@ios_ids ||= @event.user.gcm_tokens.alive_for_os_type('ios').pluck(:reg_id)
end
那变小了。在那时用define_method
减少这个是过度杀死,但如果你真的想要,那么这样做:
OS_TYPES = %w[ android ios ].freeze
OS_TYPES.each do |os_type|
method_name = "#{os_type}_ids".to_sym
instance_var = "@#{method_name}".to_sym
define_method(method_name) do
instance_variable_get(instance_var) or
instance_variable_set(
instance_var,
@event.user.gcm_tokens.where(
os_type: 'ios',
alive: true
).pluck(:reg_id)
)
end
end
这最终会变得更加混乱和代码,而不仅仅是将每个实现逐渐简化为更小的形式。如果你有几十种类型,也许你想要这样做,但老实说,这是怎么回事:
def platform_ids(os_type)
@platform_ids ||= { }
@platform_ids[os_type] ||= @event.user.gcm_tokens.alive_for_os_type(os_type).pluck(:reg_id)
end
一种可以处理N种类型的方法,您只需指定哪一种。有时特殊用途的方法不值得大惊小怪。
答案 1 :(得分:2)
您想使用Object#instance_variable_set
和Object#instance_variable_get
:
-should/didSelectItemsAtIndexPaths: