如何创建一个接受参数的 Rails 4 Concern [英] How to create a Rails 4 Concern that takes an argument

查看:47
本文介绍了如何创建一个接受参数的 Rails 4 Concern的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 User 的 ActiveRecord 类.我正在尝试创建一个名为 Restrictable 的关注点,它接受这样的一些参数:

I have an ActiveRecord class called User. I'm trying to create a concern called Restrictable which takes in some arguments like this:

class User < ActiveRecord::Base
  include Restrictable # Would be nice to not need this line
  restrictable except: [:id, :name, :email]
end

然后我想提供一个名为 restricted_data 的实例方法,它可以对这些参数执行一些操作并返回一些数据.示例:

I want to then provide an instance method called restricted_data which can perform some operation on those arguments and return some data. Example:

user = User.find(1)
user.restricted_data # Returns all columns except :id, :name, :email

我该怎么做?

推荐答案

如果我正确理解你的问题,这是关于如何编写这样的问题,而不是关于 restricted_data 的实际返回值.我会这样实现关注骨架:

If I understand your question correctly this is about how to write such a concern, and not about the actual return value of restricted_data. I would implement the concern skeleton as such:

require "active_support/concern"

module Restrictable
  extend ActiveSupport::Concern

  module ClassMethods
    attr_reader :restricted

    private

    def restrictable(except: []) # Alternatively `options = {}`
      @restricted = except       # Alternatively `options[:except] || []`
    end
  end

  def restricted_data
    "This is forbidden: #{self.class.restricted}"
  end
end

然后你可以:

class C
  include Restrictable
  restrictable except: [:this, :that, :the_other]
end

c = C.new
c.restricted_data  #=> "This is forbidden: [:this, :that, :the_other]"

这将符合您设计的界面,但是 except 键有点奇怪,因为它实际上限制了这些值而不是允许它们.

That would comply with the interface you designed, but the except key is a bit strange because it's actually restricting those values instead of allowing them.

这篇关于如何创建一个接受参数的 Rails 4 Concern的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆