Serialize_sqlite3

Wrote a small module that serializes objects (marshal) to database (sqlite3) using base64 decoding/encoding.

I have another module for serializing to file using YAML.. and will probably meld them together.

Something like this (hope it works.. I just write it):

# write it here without testing (think it should work)

class Test
  def initialize(mode: :sqlite)
    case mode
    when :sqlite
      instance_exec {
        define_method(:kakadua) { 'This is kakadua:sqlite' }
      }
    when :file
      instance_exec {
        define_method(:kakadua) { 'This is kakadua:file' }
      }
    else alert('NO!')
    end
  end
end

t = Test.new
p t.kakadua # => (should be) "This is kakadua:sqlite"

tt = Test.new :file
p tt.kakadua # => (should be) "This is kakadua:file"

Right here and now (without testing).. I wonder if I could move the ‘instance exec’-part up.. above ‘case’ + start of define_method ? Just keep String. Then end the blocks after case-end?

(with Ruby: many times when I think like that.. it works!)

Now, I have tested. and this seems to work.

alias :dsm :define_singleton_method

class Test2
  def initialize(mode: :sqlite)
    instance_eval {
      case mode
      when :sqlite  then dsm(:kakadua) { 'This is kakadua:sqlite' }
      when :file    then dsm(:kakadua) { 'This is kakadua:file' }
      else alert('NO!')
      end
    }
  end
end

%i(sqlite file).map { p Test2.new(mode: it).kakadua }

When I do..

class Test3
  def initialize(mode: nil) = ( @mode = mode )
  def method_missing(name) = ( 'This is kakadua:%s' % @mode )
end

%i(sqlite file).map { p Test3.new(mode: it).kakadua }

..it begins to feel I could almost skip i all and just do ‘if-else’.

because:

class Test4 < self
  def kakadua(mode: :sqlite) = mode == :sqlite ? 'kakadua:sqlite' : 'kakadua:file'
end

p Test4.kakadua
p Test4.kakadua(mode: :file)

Sometimes you can be so smart, you are dumb.