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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何创建Rails 4引起争论的关注点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个名为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键有点奇怪,因为它实际上限制了这些值而不是允许它们.

原文链接:https://www.f2er.com/ruby/270648.html

猜你在找的Ruby相关文章