Can't change the value of self

Discussion in 'Ruby' started by Ralph Shnelvar, Jul 15, 2010.

  1. Ok ... I've googled this error and I see stome explanations about usnig destructive methods ...

    I don't get it.

    Consider

    - - - -
    class UD_Config
    attr_accessor :container_list
    attr_accessor :screen_x, :screen_y, :screen_width, :screen_height

    @@config_filename = 'config.yml'

    def initialize
    debugger
    if File.exists? @@config_filename
    config_yaml_str = IO.read(@@config_filename)
    self = YAML::load( config_yaml_str ) # This line seems to be the problem
    else
    set_defaults
    end
    end


    def write_me
    yaml_obj = YAML::dump( self )
    File.open(filename,"w") { |f| f << yaml_obj }
    end

    private
    # call this if there is no config file
    def set_defaults
    screen_x, screen_y, screen_width, screen_height = 30, 30, 600, 500

    @container_list =
    %w(
    c:\abc\def.udd
    d:\def\ghi.udd
    f:\\ghi\jkl.udd
    )
    end
    end

    - - - -


    I have been taught that "an object should take care of itself" ... what's the right way to do what I want?
     
    Ralph Shnelvar, Jul 15, 2010
    #1
    1. Advertising

  2. Ralph Shnelvar wrote:
    > I have been taught that "an object should take care of itself" ...


    It can take care of itself, it can't turn into someone else :)

    If YAML.load is returning an instance of class UD_Config directly, then
    just return that to the user. Make a class method, so they call

    res = UD_Config.load(...)

    instead of

    res = UD_Config.new(...)

    Otherwise, YAML.load is returning some other object - possibly a Hash -
    with which you wish to initialize your new UD_Config object. So you need
    to copy values out of that object into your object's instance variables.

    If YAML.load gives an object with instance variables, you can copy them
    in a loop: look at 'instance_variables' and 'instance_variable_get' /
    'instance_variable_set'
    --
    Posted via http://www.ruby-forum.com/.
     
    Brian Candler, Jul 15, 2010
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ralf W. Grosse-Kunstleve
    Replies:
    16
    Views:
    612
    Lonnie Princehouse
    Jul 11, 2005
  2. Ralf W. Grosse-Kunstleve
    Replies:
    18
    Views:
    612
    Bengt Richter
    Jul 11, 2005
  3. Ralf W. Grosse-Kunstleve
    Replies:
    2
    Views:
    420
    Dan Sommers
    Jul 12, 2005
  4. falcon
    Replies:
    0
    Views:
    396
    falcon
    Jul 31, 2005
  5. Bart Kastermans
    Replies:
    6
    Views:
    419
    Bart Kastermans
    Jul 13, 2008
Loading...

Share This Page