Dc844b49c0e04a920a1f07b8671b8b53

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.

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 !

A3897deec9b1dbc6def9f5dfcb58bb60

spaghetticode

July 16, 2010, July 16, 2010 02:35, permalink

No rating. Login to rate!

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
D85d44a0eca045f40e5a31449277c26c

Ben Marini

July 18, 2010, July 18, 2010 20:56, permalink

1 rating. Login to rate!

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
Dc844b49c0e04a920a1f07b8671b8b53

Selman ULUG

July 26, 2010, July 26, 2010 07:34, permalink

No rating. Login to rate!

thanks a lot Ben

Your refactoring





Format Copy from initial code

or Cancel