Last active
March 4, 2018 14:34
-
-
Save nfilzi/0c6af62481c7e5ada8e468732f0f0bc5 to your computer and use it in GitHub Desktop.
Module to get decorators for POROs to make `attr_*` private
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module PrivateAttrMethodsDecorators | |
module Explicit | |
module ClassMethods | |
def private_attr_reader(*attributes) | |
attributes.each do |attr| | |
attr_reader attr | |
private attr | |
end | |
end | |
def private_attr_writer(*attributes) | |
attributes.each do |attr| | |
attr_writer attr | |
attr_writer_method = "#{attr}=" | |
private attr_writer_method | |
end | |
end | |
def private_attr_accessor(*attributes) | |
attributes.each do |attr| | |
attr_accessor attr | |
attr_writer_method = "#{attr}=" | |
private attr, attr_writer_method | |
end | |
end | |
end | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
end | |
module Implicit | |
module ClassMethods | |
def private_attr(mode, *attributes) | |
attributes.each do |attr| | |
send("attr_#{mode}", attr) | |
case mode | |
when :reader | |
private attr | |
when :writer | |
attr_writer_method = "#{attr}=" | |
private attr_writer_method | |
when :accessor | |
attr_writer_method = "#{attr}=" | |
private attr, attr_writer_method | |
end | |
end | |
end | |
end | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
end | |
end | |
class Service | |
include PrivateAttrMethodsDecorators::Explicit | |
private_attr_reader :foo, :bar | |
private_attr_writer :baz | |
private_attr_accessor :alakazam | |
def initialize(foo) | |
@foo = foo | |
end | |
def call | |
puts foo | |
self.baz = "baz" | |
p self | |
self.alakazam = "alakazam" | |
puts alakazam | |
end | |
end | |
service = Service.new("foo") | |
service.call | |
# OUTPUT | |
# foo | |
# #<Service:0x007fb4934ff458 @foo="foo" @baz="baz"> | |
# alakazam | |
service.foo # => Undefined method | |
service.baz # => Undefined method | |
service.alakazam # => Undefined method | |
service.foo = "fou" # => Undefined method | |
service.baz = "boz" # => Undefined method | |
service.alakazam = "olokozom" # => Undefined method |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment