Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Module
- def hybrid_accessor(*symbols)
- symbols.each do |symbol|
- variable = :"@#{symbol}" # :variable => :@variable
- define_method(symbol) do |*arguments|
- return instance_variable_get variable if arguments.empty?
- raise ArgumentError, "Expected 0..1 arguments, got #{arguments.count}" if arguments.count > 1
- instance_variable_set variable, arguments.first
- end
- end
- end
- def safe_reader(*symbols)
- symbols.each do |symbol|
- variable = :"@#{symbol}" # :variable => :@variable
- #Borrow a bit from conventions I've seen and say anything appended by
- # an underscore is a "READONLY" field
- define_method("#{symbol}_") do
- return instance_variable_get variable
- end
- end
- end
- # Confusing+unoriginal syntax is confusing+unoriginal
- # Taking suggestions to improve this function
- def safe_writer(*symbols)
- symbols.each do |symbol|
- variable = :"@#{symbol}" # :variable => :@variable
- define_method("#{symbol}!") { |arg|
- instance_variable_set(variable, arg)
- }
- end
- end
- end
- class X
- safe_reader :test_var
- safe_writer :test_var
- #hybrid_accessor :test_var
- def initialize(value = :default)
- puts "RESULT OF ASSIGNMENT: #{test_var! (value)}"
- puts self.methods
- read_result = test_var_()
- puts "VALUE OF test_var: #{read_result}\n\t Compare with: #{@test_var}"
- if(read_result != value)
- puts "uhoh"
- end
- end
- end
- x = X.new("Test")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement