Skip to content

Instantly share code, notes, and snippets.

@fgarcia
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fgarcia/80449b6d2754e66f557d to your computer and use it in GitHub Desktop.
Save fgarcia/80449b6d2754e66f557d to your computer and use it in GitHub Desktop.
Hide all Virtus attributes
require 'virtus'
module PersonAttributes
include Virtus.module
attribute :name, String
attribute :age, Integer
end
class PersonModel
include PersonAttributes
end
class PersonDomain
include PersonAttributes
attribute_set.each do |att|
# Take two approaches
# Idea 1: FAIL initialize with hash sets 'nil'
private :"#{att.name}="
# Idea 2: FAIL ignored
att.options[:writer] = :private
end
end
person = PersonDomain.new(:name => 'John', :age => 30)
raise 'Name was not set' if person.name.nil?
begin
person.name = 'Foo'
raise 'Write was OK'
rescue NoMethodError
end
begin
person.age = 31
raise 'Write was OK'
rescue NoMethodError
end
@fgarcia
Copy link
Author

fgarcia commented Feb 4, 2015

The objective is to define a Virtus module with a set of attributes for Person

There are two type of Person objects, a PersonModel with setters and getters, and a PersonDomain where setters and getters are private (in the example just setters)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment