Archive for category Ruby

Getting Hash keys exchanged with values (PHP’s array_flip)

In PHP there is a nifty function that exchanges Hash keys with values: array_flip.

You can have it in Ruby easily too:

hash = {:a => 1, :b => 2, :c => 3}
> pp hash.to_a
[[:c, 3], [:a, 1], [:b, 2]]
>  pp Hash[*hash.to_a.flatten.reverse]
{1=>:a, 2=>:b, 3=>:c}

You can define it as a method of Hash:

class Hash
  def flip
     self.class[*self.to_a.flatten.reverse]
  end
end

>  pp {:a => 1, :b => 2, :c => 3}.flip
{1=>:a, 2=>:b, 3=>:c}

Beware this only works on simple scalar hashes. Check out this proposal for better way.

1 Comment

PHP5 vs Ruby

<?php

class Base {
  static function create() {
    return new self;
  }
}

class Child extends Base {}

var_dump(Child::create());

?>

vs

class Base
  def self.create
    new
  end
end

class Child < Base
end

puts Child.create

What do we get?

In PHP (PHP 5.2.9-2 (cli) (built: Apr 9 2009 08:23:19)): object(Base)#1 (0) {}
In Ruby (ruby 1.8.6 (2008-08-11 patchlevel 287) [i386-mswin32]): #<Child:0x2880610>

Hopes that PHP6 fixes this.

2 Comments

Funny Ruby

a = a

You would imagine it would raise NameError if a was not defined, right? Not! It would just set a to nil :) Evil…

No Comments

Man patinka Ruby dokumentacija :))

------------------------------------------- Object#instance_variable_set
     obj.instance_variable_set(symbol, obj)    => obj
------------------------------------------------------------------------
     Sets the instance variable names by _symbol_ to _object_, thereby
     frustrating the efforts of the class's author to attempt to provide
     proper encapsulation. The variable did not have to exist prior to
     this call.

No Comments

RubyConf 2009.2 video medžiaga

http://distance.ktu.lt/vips/join.php?sr=547

Matoma tik su IE ir WMP :(

No Comments

Code is poetry

def life(person)
  give_birth :to => person
  success = bind(person, :to => love)
  try :again unless success
rescue OneIsTooOld => person
  person.die_lonely and return false
end

1 Comment

Ruby on Rails and Merb to merge for Rails 3

Ruby on Rails and Merb to merge for Rails 3.

More on Rails + Merb site.

I personally see this as very welcome move in open-source world. As one of ArtsTechnica commenters said: “Whoa, a reverse fork!” :)

,

No Comments

Calling class methods on extended class

I have a lot of models in my Rails project. And most of them can be observed. The observation behavior is defined in App::Observable module. But along the methods and constants I also needed something to be called in class that was being extended.

So I had a lot of code like this in all my models that are observable:

class User < ActiveRecord::Base
  include App::Observable
  has_many :o bservations, :as => :o bservable, :dependent => :destroy
  has_many :o bservers, :through => :o bservations
end

But as you may see it’s not very DRY. So I dug through documentation of Module and found a neat way to achieve desired behavior of running that piece of code by just including the module.

module Extender
  STUFF = "I am the stuff."

  def self.append_features(mod)
    super(mod)
    mod.call_me
  end
end

class Receiver
  def self.call_me
    puts "I was called. yay!"
  end

  include Extender
end

puts Receiver::STUFF

Now produces

I was called. yay!
I am the stuff.

As you can see the default behavior is still preserved and my custom method is called. So now you just can do:

module App
  module Observable
    def self.append_features(mod)
      super(mod)
      mod.has_many :o bservations, :as => :o bservable, :dependent => :destroy
      mod.has_many :o bservers, :through => :o bservations
    end
  end
end

class User < ActiveRecord::Base
  include App::Observable
end

Use it wisely.

No Comments

SOAP4R + Vero = crap

Naujienos iš bugland’o: naudojant soap4r gem’ą ir vero prenumeratos servisą – ėsit šūdą. Mąsčiau kodėl čia taip viskas neveikia, kol pasirodo, jog

    @rpc = SOAP::WSDLDriverFactory.new(VERO_SUBSCRIPTION_WSDL_URL) \
      .create_rpc_driver
    status, member_id, last_pay, error = @rpc.RegisterWapUser(
      VERO_SUBSCRIPTION_SERVICE_ID,
      @visitor.operator,
      @visitor.operator_id
    )

visiškai nenori sugeneruoti reikiamo pranešimo ir kaip žinutės parametrus tiesiog nusiunčia nil’us. Ko pasekoje, aišku, niekas neveikia.

Tad teko pasinaudoti ActiveWebService.

    # Fuck SOAP4R, it's buggy :(
    @rpc = ActionWebService::Client::Soap.new(VeroSubscriptionClientApi,
      VERO_SUBSCRIPTION_URL)
    status, member_id, last_pay, error = @rpc.RegisterWapUser(
      VERO_SUBSCRIPTION_SERVICE_ID.to_i,
      @visitor.operator.to_s,
      @visitor.operator_id.to_s
    )

kur VeroSubscriptionClientApi atkeliauja iš app/apis katalogo

class VeroSubscriptionClientApi < ActionWebService::API::Base
  api_method :RegisterWapUser,
    :expects => [{:ServiceId => :int}, {:Operator => :string},
      {:Phone => :string}],
    :returns => [{:Status => :int}, {:MemberId => :int},
      {:LastPay => :string}, {:Error => :string}]
  api_method :UnregisterWapUser,
    :expects => [{:ServiceId => :int}, {:Operator => :string},
      {:Phone => :string}],
    :returns => [{:Status => :int}, {:Error => :string}]
end

Tai va – žiūrėkit, neužsiraukit. Be to, soap4r turi tokį naudingą daiktą kaip request’ų debug’inimą (jog nereikėtų sniffinti)


@rpc.wiredump_dev = STDERR

, , ,

No Comments

Vaikiškai pasigirsiu

Visai smagu buvo tą dieną :)

, , ,

No Comments