加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何创建Rails 4引起争论的关注点

发布时间:2020-12-16 19:19:09 所属栏目:百科 来源:网络整理
导读:我有一个名为User的ActiveRecord类.我正在尝试创建一个名为Restrictable的问题,它接受一些像这样的参数: class User ActiveRecord::Base include Restrictable # Would be nice to not need this line restrictable except: [:id,:name,:email]end 我想提供
我有一个名为User的ActiveRecord类.我正在尝试创建一个名为Restrictable的问题,它接受一些像这样的参数:
class User < ActiveRecord::Base
  include Restrictable # Would be nice to not need this line
  restrictable except: [:id,:name,:email]
end

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

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

我该怎么做呢?

解决方法

如果我正确地理解了你的问题,那就是关于如何编写这样一个问题,而不是关于restricted_data的实际返回值.我会实现这样的关注骨架:
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,:the_other]"

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读