Skip to content

Framework Extensions Mangles

Samuel C. Tyler edited this page May 9, 2015 · 1 revision

Framework Extensions / Mangles

There are a few Padrino and Sinatra hacks that have been added to pSaMS. These are things that allow me to do the weird things like support for plugins and extended views.

Object Extension: #attempt

This is very much like andand. This basically returns nil if the sending object is nil, then try()s the message you are sending if there is one, and returns itself otherwise. Here are some examples:

2.1.2 :001 > Post.find_by_id(-1).attempt
  DEBUG -  Post Load (0.4ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1  [["id", -1]]
 => nil
2.1.2 :002 > Post.find_by_id(-1).body
  DEBUG -  Post Load (0.1ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1  [["id", -1]]
NoMethodError: undefined method `body' for nil:NilClass
        from (irb):2
        from /home/sam/.rvm/gems/ruby-2.1.2/gems/padrino-core-0.12.4/lib/padrino-core/cli/base.rb:40:in `console'
        from /home/sam/.rvm/gems/ruby-2.1.2/gems/thor-0.19.1/lib/thor/command.rb:27:in `run'
        from /home/sam/.rvm/gems/ruby-2.1.2/gems/thor-0.19.1/lib/thor/invocation.rb:126:in `invoke_command'
        from /home/sam/.rvm/gems/ruby-2.1.2/gems/thor-0.19.1/lib/thor.rb:359:in `dispatch'
        from /home/sam/.rvm/gems/ruby-2.1.2/gems/thor-0.19.1/lib/thor/base.rb:440:in `start'
        from /home/sam/.rvm/gems/ruby-2.1.2/gems/padrino-core-0.12.4/bin/padrino:9:in `<top (required)>'
        from /home/sam/.rvm/gems/ruby-2.1.2/bin/padrino:23:in `load'
        from /home/sam/.rvm/gems/ruby-2.1.2/bin/padrino:23:in `<main>'
        from /home/sam/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `eval'
        from /home/sam/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `<main>'
2.1.2 :003 > Post.find_by_id(-1).attempt(:body)
  DEBUG -  Post Load (0.1ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1  [["id", -1]]
 => nil
2.1.2 :004 > Post.find_by_id(-1).attempt{|p| p.id}
  DEBUG -  Post Load (0.3ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1  [["id", -1]]
 => nil
2.1.2 :005 > Post.find_by_id(1).attempt{|p| p.id}
  DEBUG -  Post Load (0.1ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1  [["id", 1]]
 => 1
2.1.2 :006 > Post.find_by_id(1).body
  DEBUG -  Post Load (0.2ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1  [["id", 1]]
 => "hello"

Clone this wiki locally