Casting string to IO?

I'm reading log file settings from a YAML file. Since Logger.new can
take either an IO object or string, the YAML could look like:

logger:
  output: STDOUT

or

logger:
  output: /foo/bar

The problem is that the YAML structure is loaded as strings, so if I
specify STDOUT I get a log file named "STDOUT". Is there an elegant way
around this problem? I see two less-elegant ways:

if yaml["logger"]["output"] == "STDOUT" then
  log = Logger.new(STDOUT)
else
  ...
end

or

log = eval('Logger.new(' + yaml["logger"]["output"] + ')')

etc.

I know casting is bad. Any suggestions appreciated. Thanks!

···

--
Posted via http://www.ruby-forum.com/.

Adam Block wrote:

I'm reading log file settings from a YAML file. Since Logger.new can
take either an IO object or string, the YAML could look like:

logger:
  output: STDOUT

or

logger:
  output: /foo/bar

The problem is that the YAML structure is loaded as strings, so if I
specify STDOUT I get a log file named "STDOUT". Is there an elegant way
around this problem? I see two less-elegant ways:

if yaml["logger"]["output"] == "STDOUT" then
  log = Logger.new(STDOUT)
else
  ...
end

or

log = eval('Logger.new(' + yaml["logger"]["output"] + ')')

etc.

I know casting is bad. Any suggestions appreciated. Thanks!

The problem is that you are not casting, you are dealing with
variable names (symbolic names) versus variable contents. In
that light, your solutions are fine unless you have/make a
filesystem file corresponding to STDOUT :slight_smile:

···

--
Posted via http://www.ruby-forum.com/\.

Adam Block <adam@usa.net> writes:

The problem is that the YAML structure is loaded as strings, so if I
specify STDOUT I get a log file named "STDOUT". Is there an elegant way
around this problem? I see two less-elegant ways:

[snip]

I know casting is bad. Any suggestions appreciated. Thanks!

Module#const_get might help you out:

  require 'logger'
  output = "STDOUT"
  output = Kernel.const_get(output) rescue output
  log = Logger.new(output)
  log.instance_variable_get("@logdev").dev == STDOUT # => true

- Marshall

Adam Block wrote:

I know casting is bad.

<pedant>
This is probably coercion, not casting. The latter I tend to associate with conversion between almost-but-not-quite-compatible and maybe-but-we-can't-tell-until-we-try-compatible types.
</pedant>

David Vallner

Very nice! Thanks!

···

  output = Kernel.const_get(output) rescue output

--
Posted via http://www.ruby-forum.com/\.