Access to the Rack session from RSpec  

By Stoyan Zhekov · January 26, 2012

To access Rack application session variable (env['rack.session']) in your RSpec tests:

Re-define session():

# spec/spec_helper.rb
def session
  last_request.env['rack.session']
end

And use the new method:

# spec/app_spec.rb
describe :sessions do
  context "set session" do
    it {
      get '/session/stuff'
      session[:mystuff].should == "stuff"
    }
  end
end

Startup Weekend Kyoto  

By Stoyan Zhekov · August 8, 2011

Last weekend I participated in the Startup Weekend Kyoto event. Some short notes on that:

In general it was great - even more that I expected. Usually I'm going to "otaku"-type events - Ruby kansai, RubyKaigi. With otaku I mean not the obsessive type of guys, who are accumulating anime figures and stocking the moemoe girls, but mostly to group of people, having passion for something common, in my case Ruby programming language. There was a Ruby kansai meeting in the same time, but I decided to try something different. And here we go - Startup Weekend Kyoto.

Day 1

I've got a ticket and start to prepare. According to their site, the needed stuff was slides and the presentation are going to be 2 minutes long. I made the slides, rehearsal my speech and just an hour before I go , I've got an e-mail: "The presentations will be 60 sec long and only verbal, no slides"!? What the hack... It is not an excuse for my pitching failure, just it helps a lot...

Initial pitching...It was bad :( 1 min per person...Not good. Also there was no professionalists who can choice an initial set of ideas the teams will work on. Hm, I know, it have two sides - freedom vs effective. I mean when trying to build a pyramid, the base matters. Examples: all that reality TV shows ("American Idol" etc.) - judges participating in the initial filtering. More good ideas from the beginning means maybe more successful startups in the end, I guess... But freedom also is important...Never mind, just to put here a links to my slides, so maybe somebody can work on the implementation:

Day 2

So 9 ideas was chosen and we started working on them. I think, we form a very good team:

  • Mariko Iwano - "The Boss". Team management
  • Yuki Nishimura, Syuhei Mitaka, Ryo Sakamoto - business planning
  • Takao Sumitomo - Web design, presentation slides
  • Syo Ikeda - iPhone application
  • Stoyan Zhekov (me) - web application

It was very interesting to see how naturally the teams are formed. Everybody was with different backgrounds, sometimes not related at all to the current task. For example, Nishimura san is C programmer, but he done a very good job figuring our business strategy. Sumitomo-san is Android developer, but make us beautiful presentation slides. Ryo ans Syuhei are still students, but helped Nishimura-san a lot. Syo made so good iPhone application mockups, that I by mistake tried to press the buttons, because I thought it is real. Iwano-san, "The Boss" show us how to manage a team with a soft, women power. Some pictures:

Me-new logo Brainstorming iPhone mockup

Maybe we spend too much time talking, because we couldn't finish until 23:00, so I needed to work home until 3 o'clock next morning, but still it was very good work that day.

Day 3

"Judgment day"...A lot of emotions...Excitement and disappointment... And the winners:

First price for "Umbrella station" ("傘ステ" in japanese). The idea was interesting from the beginning. I talk with Satoru Miyamoto (@darkukll) on the initial pitching. His original idea was to put some special device inside the umbrellas, so you can share their usage - leave them on public places and use them when needed. I think I gave him the idea to put the device not inside the umbrellas, but in the stand on the public place. He told me "Great idea" and for 3 days his team done a magic! They got a working prototype for 3 days! RDIF tags (or maybe barcodes) on the umbrellas, sensor with Java program to read the codes, a management screen, showing in real time who get which umbrella...Everything was working on the final presentation. Just for 3 days! Very well done job.

Another winner - @dekilog - helping lazy people to continue doing some activities - studding, jogging etc. Hm, in the beginning, on the initial pitching, I thought it is not a good idea, but the team done a very good job making a good final product - an iPhone application and strategy for using it - tips from more advanced people, preset data from a professionalists (couches etc.)...Still don't think it will help with laziness, but who knows...

And the last winner - "Toilet Panic". This idea was bad...From the beginning. And in the end, the implementation also was bad...Not sure who decided it deserve an award. The idea in general - when you work on some public place (for example "Starbucks") and need to go to the bathroom, you need somebody to take care for your left computer. Pretty common problem, I can understand this. I know it IS a problem. But the solution: an iPhone application messaging ALL PEOPLE AROUND YOU, to announce you are going to the toilet and you are leaving your computer! Will you ever use such an application? It is fixing a personal problems by escalating them by power of 10. You are too shy to ask the guy, sitting near to you, so you are messaging everybody around you, that you have a personal needs! Clever, a ;) They get some "professional" marketing and promotion guy, who was claiming, he will start to work immediately, from the next day, to spread "the product" first in Tokyo and next worldwide. So watch your back - "Toilet Panic" - coming soon to your iPhone and to your "Starbucks" place!

But let's finish with more positive thoughts: I didn't know there are so many incubator houses, angel investors and people, who want to work on startups in Japan. Now I know the future is bright - Japan is moving fast (and to be more specific: Kyoto and the Kansai area, where I'm living), there are a lot of people with ideas and people, willing to hope implementing these ideas. So like one famous company logo says - "Just do it!"

RubyKaigi 2011 notes - Day 2, Part 2  

By Stoyan Zhekov · July 21, 2011

Warning: this is not official RubyKaigi 2001 report, just some personal notes on stuff, interesting (maybe only) for me. All RubyKaigi 2011 videos are available online - see them for yourself.

See also

5 years know-how of RSpec driven Rails app. development.

by Kyosuke Morohashi @moro

Some tips:

Write model unit tests first

Why? Because common practice in Rails is "Skinny Controllers, Fat Models". Means most of the code will be in the models: starting with model unit tests will give you pretty good "kick start" and pretty good code coverage.

Use different strategies for different types of data

In general data, you need for your model tests, can be divided on:

  • Master data - created and updated rarely, does not have a lot of dependencies. Use scaffold to create it
  • Resource data - main objects in your system. Write tests mostly for this group
  • Event data - represent relations between resources (has_many :through)

What exactly strategies to use for creating different types of data:

  • Fixtures - YAML. good speed, difficult to maintain - master data
  • Fixture replacements - Fabrication library, Factory Girl. Flexible (creating objects), but difficult to use correctly. Slower to load. resource and event data
  • before setup block in the tests code - data, specific for every test. quick, but a little difficult to maintain. event data

Share your testing context

Name your datasets - let(). This will hide the implementation and you can just call them by name:

let(:answer) { 42 }
specify { answer.should == 42 }

RSpec has something called shared context

shared_context "Subscribe to a course" do
    let(:student) { Fabricate(:student) }
    let(:event) { Fabricate(:event) }
    let(:course) { event.courses.first }

    before do
        student.subscribe(course)
    end
end

Usage of this context:

describe Student do
    include_context "Subscribe to a course"
    ....
end

More info: Idiomatic shared state in RSpec

Use Cucumber for end to end tests

Test rest of you code with Cucumber

If you are in Tokyo, maybe you'll be interested to work for Eiwa System Management. They have also an interesting blog covering agile development practices

Also for Tokyo people - take a look on Rails Tokyo.

May a test be with you

Advancing Net::HTTP

by Yehuda Katz @wycats

@wycats likes Net::HTTP , but I like EventMachine and the whole em-* suite.

Good about Net:HTTP : pure Ruby, support for threads, SSL, proxies, keepalive etc. Have some bug with gzip

End of block in ruby cleanup resources - closing files, sockets etc.

Example for keepalive:

Net::HTTP.start(host, port) do |http|
    http.get('/path') do |chunk|
        ....
    end
    # keepalive if HTTP 1.1
    http.get('/another') do |chunk|
        ...
    end    
end        # cleanup: close the socket

The whole story started, because Mr.Katz company wanted to build a single-threaded streaming proxy with Webrick and Rack. Problem: Net::HTTP is using blocking read:

http = Net::HTTP.start(host, port)
http.get('/path')   # block

Same happens even if using the lowest end API - Net::HTTPGenericRequest

Yehuda Katz's solution: Net2::HTTP library - forked and patched Net::HTTP . The general idea is to close the response, only if get() is used with a block, something like:

http.get('/path') do |chunk|
    ...
end

Otherwise - do not touch the resource, we will manage it by ourselves.

Async - the ability to make a request for a specific chunks of the stream, not for the whole stream and wait

# first open f1 and f2
foo, bar = "", ""
until f1.eof? && f2.eof?
    begin
        IO.select [f1, f2]
        foo << IO.read_nonblock(1024)
        bar << IO.read_nonblock(1024)
    ...
# close f1 and f2

IO.read_nonblock is the key. Hm, interesting - this will support select() - universal but slow. What about epoll(), kqueue() etc.?

General purpose "Reactor"

A general was to handle a bunch of resources - sockets etc.: when something is available - read it, until everything is done.

# open f1 and f2
foo, bar = "", ""
callbacks = {}
callbacks[f1] = proc { |chunk| foo << chunk }
callbacks[f2] = proc { |chunk| bar << chunk }
until callbacks.empty?
    read, _ = IO.select callbacks.keys
    read.each do |io|
        begin
            callbacks[io].call io.read_nonblock(1024)
        rescue EOFError
            io.close
            callbacks.delete io
ennnd

Ruby Nonblocking Protocol

Objects, implementing the proposed API, can be pushed to the "reactor"

  • to_io - already implemented. Return an object, that can be passed to IO.select
  • read_nonblock - nonblock read
  • close - cleanup resources
  • eof? - are we in the end of the file
  • Errno::EWOULDBLOCK - it will block
  • EOFError - we are on the end of the file

Misc

Short notes, too small to have a separate chapter

The best practice of building mobile website with jpmobile by Shin-ichiro Ogawa

Tried to use jpmobile in one of my latest projects, but with current smart phones (browser UserAgent for example) didn't help me very much :(

Lightning Talks

RubyKaigi 2011 notes - Day 2, Part 1  

By Stoyan Zhekov · July 20, 2011

Warning: this is not official RubyKaigi 2001 report, just some personal notes on stuff, interesting (maybe only) for me. All RubyKaigi 2011 videos are available online - see them for yourself.

Ruby goes to Hollywood

by Elise Huard @elise_huard , a beautiful lady from Belgium

Actors with Ruby presentation slides

Filming is a parallel process - if you film a scenes in parallel, you'll save money - "Time is Money"

Sleeping barber problem

But the berber will be with some "small issues" - cutting the customers heads from time to time. Hahaha! Berber with issues

Software choices:

  1. Ruby
  2. Erlang (but with a taste of Ruby)
  3. Scala

In the moment, Celluloid seems the best choice:

class Barber
    include Celluloid::Actor
    attr_accessor :status 

    def initialize(shop)
        @shop = shop
    end

    def cut_customer(name)
        puts " cutting customer #{name}"
        sleep(rand(5))
        accident = rand(2)
        if accident
            puts " finished cutting #{name}"
        else
            puts " *** whoops, chopped #{name}s head off ***"
        end
        shop.customer_leaves!
    end
    (...)
end

There is no meaning in using concurrency with CRuby. Maybe using Erlang with a Ruby flavour is a better idea. Erlang is based on actors by default. One brilliant Elise's idea is: in fact you can use all akka primitives from JRuby!

Keywords to check: "Software transactions memory", "Tuple spaces"

Drip: Persistent tuple space and stream.

by Masatoshi Seki @m_seki

Didn't understand the talk very much. In general there is Drip - something like an intelligent logger - you can only dd, but not modify or delete.Still cannot figure what this can be used for.

Ruby on Rails development that doesn't hurt

by Akira Matsuda @a_matsuda

Talking not for developing with Rails, but for developing Rails framework itself - plugins and framework changes.

"Social Coding"

Stop writing ways around in you blog and start sharing your monkey patches - push them to the upstream!.

Communication by codes exchange.

  • Read 'git log' every morning (sort of newspaper)
  • hub: git + hub = github - a command line utility which adds GitHub knowledge to git.
  • DHH is not creating Rails, he is just a social face ;) - look in the logs who are real commiters
  • Live on the edge. Edge is fun!
  • Start with writing a gem
  • BDD = Book Driven Development - write a book, will help you to improve your knowledge

Notes for myself:

  • maybe will try Rails 3.1 HackFest ;)

  • list of project remote branches:

    $ git remote show origin

  • track remote branch

    $ git checkout --track -b remoteBranch origin/localBranch

Writing Friendly Libraries

by Eric Hodel @drbrain

Names

  • library_name => class LibraryName
  • library_name-extension => class LibraryName::Extension

Versions

X.Y.Z - X for incompatible changes, Y for new features, Z for bug fixes

Extensibility

  • Hooks
  • Plugins - help you register hooks.

Example from rdoc (showing Gem.find_files usage):

plugins = Gem.find_files "rdoc/discover"
plugins.each do |p|
    begin
        load p
    rescue
        warn "error #{...}"
ennd

Use 'Gem.data_dir' for the shared data

Hoe gem can help you with most of the release tasks:

  • sure tests passed
  • manifest is complete?
  • create the gem
  • upload the gem
  • tag the release
  • upload the documentation

With hoe:

rake release VERSION=X.Y.Z

Road to the Ruby Master

by Yutaka Hara @yhara

The talk was not so interesting for me, but the slides was presented with BiwaScheme - Scheme interpreter written in JavaScript! Means it will work in your browser! Example are the presentation slides themselves.

Notes for myself:

  • "The pristine command compares the installed gems with the contents of the cached gem and restores any files that don’t match the cached gem’s copy...If you have made modifications to your installed gems, the pristine command will revert them."

    $ gem pristine rails

  • environment information

    $ gem env

Efficient JavaScript integration testing with Ruby and V8 engine.

by Chris Kowalik @nu7hatch

Cool polish guy, working in Uruguay for Cubox.

Using Showoff for presenting. See also presentation slides themselves.

If you don't want to wait an hours until your Selenium tests are finished, use Mike, the Headless Browser.

Chris is "optimization otaku" ;) - want to optimize everything around him for speed. He likes HtmlUnit(java) and V8 JS engine

See also

Note 1: 2nd day report became pretty long, so I decided to split in on two parts. Yehuda Katz (@wycats), Kyosuke Morohashi (@moro) and Lightning talks will be in the second part. Stay tuned...

Note 2: will be interesting to combine all RubyKaigi presentations Vimeo videos with Slideshare slides, using Zenpre, introduced during day 1.

RubyKaigi 2011 notes - Day 1  

By Stoyan Zhekov · July 19, 2011

Warning: this is not official RubyKaigi 2001 report, just some personal notes on stuff, interesting (maybe only) for me. All RubyKaigi 2011 videos are available online - see them for yourself.

Ruby ruined my life

by Aaron Patterson @tenderlove

I was a little suspicious, because the title is hm, questionable, but it was a GREAT presentation by Aaron Patterson. You don't know Aaron? Hi is DrBrain's uke for practicing Judo, hahaha. Joke, he is Rails core developer, member of Seattle.rb brigade.

Next version of Ruby 1.8 and 1.9

There was some CRuby team "live meeting" on the stage. Real time negotiations ;)

1.8.6

Maintained by Kirk Haines (@wyhaines). There will be just one more release (in the next 2 months) - fixing as more bugs as possible. After this 1.8.6 will die.

1.8.7

About 1.8.7 EOL

1.9.3

New features:

2.x

Matz is banned from trunk. He will receive his own branch to play with. Eventually some day this branch will become 2.0. Trunk is now Yugui-san's territory (there was a funny propose to rename it YuRuby).

Other facts (from the last day Matz's presentation):

  • RiteVM sources are already in the private GitHub repository. Until the end of this year they will be opened
  • Heroku will hire a team of programmers, working full time on Ruby
  • The number 1 Ruby commiter, Nakada-san, is first in this team. Until now, he was working on Ruby in his free time and done more commits, then Matz, so imagine, when he work full time on Ruby...

Large-scale web service and operations with Ruby

by Yuichi Tateno (secondlife) @hotchpotch

CookPad is one of the biggest Ruby on Rails driven sites in Japan. More about their system:

  • Ruby 1.8.7
  • Rails 2.3 - HAML, SASS, jQuery
  • Passenger 2.2 - old, but fast and stable. Good enough for them - Lesson learn: do not update without a reason
  • MySQL 5.0
  • memcached
  • CDN by Akamai
  • Varnish 2.1.5 for caching
  • searching by Solr
  • Capistrano for deployment
  • some mysterious mod_tofu
  • Jenkins CI for continuous integration.

for more: CookPad technical blog

Shipping at the Speed of Life

by Corey Donohoe @atmos

Some GitHub internals. A lot of interesting tools (google for more information) - BroswerMod (Akamai), Pingdom, Propane (extendable JS), Haystack (exceptions logging), Silverline

Deploying frequently

Not doing whole repository cloning, but:

git fetch origin
git reset --hard origin/master

Not only the master branch, but also topic branches. - origin/topic

Heaven - wrapper around capistrano for easy branch deployments:

heaven -a github -e production -h fe -b my_branch

Using Campfire for communications

For small teams it cost just $12 - cheap and easy to use. Hubot - communication bot, can do distributed execution.

for more: GitHub blog

Toggleable mockups

by Andy Delcambre @adelcambre

  • Mock - Objects that act like a real thing, but with expectations on the calls made
  • Stub - Replacing certain methods on an object with dummy data

Mock on rack level. Some good tools:

Mission critical Ruby application

by @emorima

Some crazy setup - 100 processes X 100 threads in each, listening on UDP sockets for sensor data.

YamiRubyKaigi: Smells Like Teenage Spirit

"Yami" is for Dark, not delicious. It is about Dark Side Ruby addicts - unusual Ruby usage.

Some video footage:

Presentations

RubyKaigi is dead! Long life RubyKaigi!

There will be no more RubyKaigi, but next summer there will be Sapporo Regional RubyKaigi, which will try to continue the tradition. So you still have a chance to visid Japan and talk with great people about Ruby, Programming, Life and so on.

The whole RubyKaigi web site system is open-sourced. Fork it, customize it and use it.

See also

Archive