require 'yaml'
module Actions
attr_accessor :prefix
def getline
prefix + self.to_yaml
end
def to_yaml_style
:inline
end
end # Actions
def extender(*objs)
objs.each do |obj|
obj.extend(Actions)
obj.instance_variable_set(:@prefix, '#')
end
end
h = {:message => "I am a Hash"}
a = %w(I am an Array)
s = "I am a String"
extender h, a, s
puts h.getline
puts a.getline
puts s.getline
# "#--- {:message: I am a Hash}" ok
# "#--- [I, am, an, Array]" ok
# "#--- !str {str: I am a String, :@prefix: "#"}" not ok must be "#--- I am a String"
Refactorings
No refactoring yet !
spaghetticode
July 16, 2010, July 16, 2010 02:35, permalink
Quick & dirty:
module Actions
attr_accessor :prefix
def getline
prefix + to_custom_yaml
end
def to_yaml_style
:inline
end
def to_custom_yaml
is_a?(String) ? "--- #{to_s}" : to_yaml
end
end # Actions
Ben Marini
July 18, 2010, July 18, 2010 20:56, permalink
String is not outputting the way you want because `#to_yaml_properties` (called in `String#to_yaml`) is detecting the `prefix` accessor. Here is one way around that...
module Actions
attr_accessor :prefix
def to_yaml
prefix + super
end
def to_yaml_style
:inline
end
def to_yaml_properties
[]
end
end # Actions
I want to extend givin instances with my specified Actions module working on Array and Hash but on String returning with my modules construct can't find the solution help please.