8

Ho una classe ActiveRecord chiamata Utente. Sto cercando di creare un problema chiamato Restrictable che prende in alcuni argomenti come questo:Come creare un Rails 4 Preoccupazione che accetta un argomento

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

Voglio quindi fornire un metodo di istanza chiamato restricted_data che possono eseguire alcune operazioni su tali argomenti e restituire alcuni dati. Esempio:

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

Come farei per farlo?

risposta

13

Se ho capito la tua domanda correttamente questo è su come scrivere una tale preoccupazione, e non per il valore di ritorno effettivo di restricted_data. Vorrei implementare la preoccupazione scheletro come ad esempio:

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 

Quindi è possibile:

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

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

Che sarebbe conforme con l'interfaccia che hai disegnato, ma la chiave except è un po 'strano perché in realtà è limitare tali valori invece di permetterli.