You are here: Blogsphere Longtail

Rails BlogSphere

BlogSphere

Keep up to date with your favourite Rails bloggers in context.

Read more about how it works


Manipulowanie czasem w testach w aplikacjach Ruby

by Jakub Kosiński | 2 days ago | Read more

Czasem, szczególnie podczas pisania testów, zachodzi potrzeba manipulowania czasem, np. podczas testowania metod, które mają zwracać posortowane względem czasu utworzenia obiekty ActiveRecord.

W ostatnim projekcie podczas pisania spec-ów modeli korzystałem z takiego tworu:

describe SomeClass do
  describe "by_date" do
    it "should return objects sorted by creation date" do
      Time.advancing_by_days(-1) do
        @earlier = SomeClass.new(:some => "values")
      end
      @normal = SomeClass.new
      Time.advancing_by_days(1) do
        @later = SomeClass.new(:some => "other value")
      end
      SomeClass.by_date.should == [@later, @normal, @earlier]
    end
  end
end

O ile mi wiadomo, Railsy nie mają standardowo wbudowanych klas do manipulowania czasem, czy metodą Time.now.

Stworzenie metod realizujących powyższą funkcjonalność jest bardzo proste. Wystarczy stworzyć plik, np. time_extensions.rb z poniższą zawartością:

require 'time'

if !Time.respond_to?('old_now')
  Time.class_eval {
    @@advance_by_days = 0
    @@advance_by_minutes = 0
    cattr_accessor :advance_by_days, :advance_by_minutes

    class << Time
      alias old_now now
      def now
        if Time.advance_by_days != 0
          return Time.at(old_now.to_i + Time.advance_by_days * 60 * 60 * 24 + 1)
        elsif Time.advance_by_minutes != 0
          return Time.at(old_now.to_i + Time.advance_by_minutes * 60)
        else
          old_now
        end
      end
      def advancing_by_days(days=0)
        Time.advance_by_days = days
        yield
        Time.advance_by_days = 0
      end
      def advancing_by_minutes(minutes=0)
        Time.advance_by_minutes = minutes
        yield
        Time.advance_by_minutes = 0
      end
    end
  }
end

Jak widać korzystamy z możliwości, jakie daje monkey pathing i modyfikujemy standardową metodę Time.now, uprzednio tworząc do niej alias. W powyższym kodzie oprócz zmiany czasu o zadaną liczbę dni, możemy zmieniać go o zadaną liczbę minut.

Aby korzystać z powyższych metod w spec-ach aplikacji railsowej, wystarczy wrzucić plik z powyższym kodem do katalogu spec aplikacji i dopisać do pliku spec_helper.rb linijkę:

require 'time_extensions'

Cvoidds1 Protest tomorrow over bill C-61

by Guy Davis | 2 days ago | Read more

I'll be heading to Jim Prentice's Stampede Breakfast tomorrow morning with the rest of the "Fair Copyright for Canada" group to let him know my thoughts on his Canadian DMCA. Since he's hidden himself away and hasn't consulted with the public on his bill, this is how we'll hopefully get him to listen to reason.


Pixelhandler128 Responsing to FastCompany’s Big Idea - Business email will eventually be replaced… like Twitter and company wikis.

by Bill Heaton | 2 days ago | Read more

I would suggest that businesses seriously consider self hosted wiki/forums or other web-based application for collaboration among teams and also to support a positive company coulture. When employees are plugged-in often this generates a sense of belonging and ownership. I also believe that using an internal server to run a chat service along the lines [...]

Dsc02897 Wordle

by Gunnar Wolf | 2 days ago | Read more

Via Planetalinux.mx, I read this post by César Espino refering to Wordle.
Quoting from Wordle's main page:

Wordle is a toy for generating “word clouds” from text that you provide. The clouds give greater prominence to words that appear more frequently in the source text. You can tweak your clouds with different fonts, layouts, and color schemes. The images you create with Wordle are yours to use however you like. You can print them out, or save them to the Wordle gallery to share with your friends.

I could not resist it. I even went to a computer with a Java runtime installed.

The application is very nice and usable, although its startup time is frankly irritating (specially as there is no feedback on why it's not loading). Anyway, the results are quite beautiful!

Frantisek-malina3 PayPal hack

by Frantisek Malina | 2 days ago | Read more

Many users complained about the PayPal payment page being designed in a way that intentionaly hides the credit card payment option and forces users to login with a PayPal account. Bad for PayPal as they are wrong thinking think this will increase their user base, double evil for online merchants conversions. I’ve hacked (not cracked) [...]

Frantisek-malina3 PayPal hack

by Frantisek Malina | 2 days ago | Read more

Many users complained about the PayPal payment page being designed in a way that intentionaly hides the credit card payment option and forces users to login with a PayPal account. Bad for PayPal as they are wrong thinking think this will increase their user base, triple evil for online merchants conversions. I’ve hacked (not cracked) [...]

Pixelhandler128 July podcast posted: Winning t…

by Bill Heaton | 2 days ago | Read more

July podcast posted: Winning the #1 Search Engine Result for Your Key Phrase - http://pixelhandler.com

Pixelhandler128 Winning the #1 Search Engine Result for Your Key Phrase

by Bill Heaton | 2 days ago | Read more

Internet Marketing Report and Social Media Highlights Newsletter - July 2008 This newsletter will mail out the first week of each month, please visit the link below to opt-in http://lists.pixelhandler.com ‘Bill’s Internet Marketing Report’ - Winning the #1 Search Engine Result for Your Key Phrase -  Strategies and topics relating to the happenings I experience in the race [...]

danhigham: Adding a message to get RSS working from Twitter

by Dan Higham | 2 days ago | Read more

danhigham: Adding a message to get RSS working from Twitter

Ryan-orange-large NeoOffice

by Ryan L. Cross | 2 days ago | Read more

NeoOffice

Ryan-orange-large GrApple Yummy (blue) :: Firefox Add-ons

by Ryan L. Cross | 2 days ago | Read more

GrApple Yummy (blue) :: Firefox Add-ons

Ryan-orange-large Firefox 3 optimized builds for G5 / Intel

by Ryan L. Cross | 2 days ago | Read more

Firefox 3 optimized builds for G5 / Intel

Mihael push me pull me

by Miha Plohl | 2 days ago | Read more

na domačem meku

git clone --bare projektich projektich.git
scp projektich.git nekdo@odnekogaserver.com:/home/nekdo/
na kerem koli kompjuteru pač

git clone nekdo@odnekogaserver:/home/nekdo/projektich.git mojklonprojekticha
cd mojklonprojekticha
git push
git pull

My120_135 RE: RE: Server Side Software Engineer

by Ruslan Voloshin | 2 days ago | Read more

думаю требование знания языка на котором написаны требования, так что елси кто не сможет прочитать то и не напишет, хотя у меня с английским тоже не валом дела обстоят. В наших школах до сих пор готовят партизанов на немецком языке :(

My120_135 Чудесная новость

by Ruslan Voloshin | 2 days ago | Read more

Нас добавили в dmoz каталог Top: World: Russian: Компьютеры: Программирование: Языки: Ruby Мы первые :) по сему предлагаю просто хитрый метод который позволяет с помощью hpricot проверять елси лы ваш сайт в каталоге. def dmoz_catalog #http://search.dmoz.org/cgi-bin/search?search=u%3Acocos.com.ua page = get_page('search.dmoz.org', "/cgi-bin/search?search=u%3A#{@host}") doc = Hpricot.parse(page.body) cat = doc.search("ol[@start='1']/li/b") cat.empty? ? nil : cat.html end def get_page(host = @host, path = @path, port = @port) port ||= 80 begin req = Net::HTTP::Get.new(path) puts "Request HOST #{host}" puts "Request Path #{path}" res = Net::HTTP.start(host, port) {|http| http.request(req) } rescue Exception => e @@logger.info(e) nil ensure return res end end # НУ и вызов метода собственно links = Link.new links.set_page('http://rubyclub.com.ua') puts links.dmoz_catalog В результате напечатается или ничего или html ссылка на раздел каталога в котором находится сайт.
dmoz каталог

Star Wars Museum

by Scott Hacker | 2 days ago | Read more

Spent a day of our recent vacation at the Minnesota Museum of Science’s Star Wars exhibit - the largest collection of actual Star Wars props and models ever assembled. Miles was jumping out of his skin with excitement, seeing actual/life-sized land speeders and battle droids, scaled down ship models used by ILM in [...]

My120_135 RE: Server Side Software Engineer

by Ruslan Voloshin | 2 days ago | Read more

Между прочим в сообществе приянто общаться на его (сообщества) языке. При этом никто не запрещает упомянуть об требуемом уровне знания англ/нем/идиш/итд языка.

My120_135 RE: RE: FCKeditor on Rails

by Ruslan Voloshin | 2 days ago | Read more

Язык меняется насткойками в файле конфига в public папке к стати конфиг имеет вроде расширение JS БОлее подробно сейчас не помню.

My120_135 RE: стили в in_place_editor

by Ruslan Voloshin | 2 days ago | Read more

А ты посмотри что пишется в HTML с помощью firebug и увидишь чем можно воздействовать.
firebug

My120_135 RE: FCKeditor on Rails

by Ruslan Voloshin | 2 days ago | Read more

Привет! Не подскажешь, как изменить язык итнерфейса в FCKeditor?

2008년 7월 4일

by Heungseok Do | 2 days ago | Read more

  • 동사무소 온다고 잠깐 걸었는데 땀이 줄줄 흐른다(더워 me2photo)2008-07-04 09:44:47

  • 친구들은 페이지에 올라온 shinvee보고 XPBE Wubi 로 구글에서 검색했더니 shinvee님 글이 맨 처음 나온다. (이 멍미! 벌써 긁어 간거? 그 모습을 본 톱내의는 “구글 불쌍하다”)2008-07-04 18:26:11
  • 15년 정도된 잠바를 아직도 입는다. 패션에 신경 좀 써야겠다.(개발자 패션)2008-07-04 19:38:07
  • 미투데이 방문한 씨에 다즐링 옹들(옹들 me2photo)2008-07-04 19:51:30

  • 이 글은 꽃띠앙님의 2008년 7월 4일의 미투데이 내용입니다.

    <!-- end of daily_digest -->

    User Interface design for the iPhone

    by Rahoul Baruah | 2 days ago | Read more

    John Gruber finds a great example of iPhone UI design. Sometimes you have to wonder what goes through people’s heads. http://www.flickr.com/photos/gruber/2635257578/

    Me "4th of july is the best holiday— no need to buy presents, or spend time w/ the relatives, or..."

    by John Reilly | 2 days ago | Read more

    “4th of july is the best holiday— no need to buy presents, or spend time w/ the relatives, or dress up, or go to church… just a day off work, fireworks, nice weather and food.”

    - My Linh Pham

    Salvem os Desenvolvedores

    by Luiz Arão A. Carvalho | 2 days ago | Read more

    Entrando na campanha… A incompatibilidade de alguns browsers acabam comprometendo a eficárcia e a produtividade dos desenvolvedores então galere utilizem sempre os browsers atuais é bom pra gente mas é melhor ainda para você! Save A Developer. Upgrade Your Browser. Melhor de Segurança Melhor Interface Navegador com Abas Bloqueia popup Download Melhor Segurança Plugins personalizáveis Navegação com Abas Download Improved Security Enhanced JavaScript Functionality Tabbed Browsing Download Improved [...]

    Balcony How to nap - Boston.com

    by Patrick Curtain | 2 days ago | Read more

    http://www.boston.com/bostonglobe/ideas/naps/


    --p

    http://www.patrickcurtain.com/
    patrick@patrickcurtain.com
    +1-360-521-9625

    Some things are inherently complicated and slow ... put them in the right place

    by Alex Rothenberg | 2 days ago | Read more

    One of the first lessons I learned when I started working as a software developer professionally was that you don't always have to make an action fast, sometimes its just enough to make it seem fast to a user. This lesson was learned in the 1990s in the context of a Windows application. What we did was quickly draw part of the screen (or a splash image) immediately then do the time consuming work in the background so that by the time the user was ready to interact with the application we'd be ready for them.

    Recently I was reminded of this lesson on a website I'm working on. We have a complicated report to show on the user's homepage. My first implementation involved generating the report in real-time when the page is loaded but this was very slooooow. Some profiling and analysis let us make it somewhat faster but not fast enough.

    I was stumped until I remembered my old lesson. If it wasn't possible to generate the report quickly, perhaps we could do it sometime when the user wouldn't mind.

    Luckily this is a Rails application and ActiveRecord Callbacks make it easy to do this. I could pregenerate the report and update a portion of it each time something is saved. Users expect a save to take some time and don't do it that often. Then generating the homepage becomes just a simple matter of displaying the existing rows.

    My applicatiion looks something like this.

    #app/models/person.rb & any other models that affect the report
    #When a Person changes tell the ReportGenerator add/delete/update the appropriate rows
    class Person <>after_destroy {|person| ReportGenerator::Person.destroyed(person)}
    after_create {|person| ReportGenerator::Person.created(person) }
    after_update {|person| ReportGenerator::Person.updated(person) }
    end


    #lib/report_generator.rb
    #The complicated (and slow) logic goes here
    module ReportGenerator
    class Executive
    def destroyed(executive)
    #figure out which rows to delete from the report and persist with the Report model
    end
    def created(executive)
    #figure out which rows to add to the report
    and persist with the Report model
    end
    def updated(executive)
    #figure out which rows to update in the report
    and persist with the Report model
    end
    end
    #Similar classes corresponding to the other models that trigger recalculations would go here
    end

    #app/models/report_row.rb
    #app/controllers/report_controller.rb
    #app/views/report/index.html.erb
    #Models the persisted rows in my report and the controller and view to display it


    The interesting insight for me is that when optimizing there are sometimes hard problems that can't be solved. Its important not to lose sight of the goal you're aiming at (a satisfying user experience) and that sometimes involves spending the computational time somewhere where the user won't mind.

    Www-rolson Rails-doc.org is my new Rails Reference

    by Robert Olson | 2 days ago | Read more

    When working with a framework as large as Ruby on Rails its necessary to have a reference close by for… well just about everything. Until until recently I was a big fan of gotAPI.com because I really appreciated the Ruby and Rails reference tied together. However, the Javascript autocomplete on their search box is broken [...]

    Blues [Flickr]

    by Andreas Aderhold | 2 days ago | Read more

    Ro Dinal posted a photo:

    Blues

    Blues [Flickr]

    by Andreas Aderhold | 2 days ago | Read more

    Ro Dinal posted a photo:

    Blues

    Greens [Flickr]

    by Andreas Aderhold | 2 days ago | Read more

    Ro Dinal posted a photo:

    Greens

    Blues and Greens [Flickr]

    by Andreas Aderhold | 2 days ago | Read more

    Ro Dinal posted a photo:

    Blues and Greens

    Blues, Greens, Whites [Flickr]

    by Andreas Aderhold | 2 days ago | Read more

    Ro Dinal posted a photo:

    Blues, Greens, Whites

    Blues, Greens, Whites [Flickr]

    by Andreas Aderhold | 2 days ago | Read more

    Ro Dinal posted a photo:

    Blues, Greens, Whites

    Blackburn_120x180 Independence Day

    by Chris Blackburn | 2 days ago | Read more

    Happy July 4th to every American out there!

    288887654_94e759eb3c_m jen-jorge-laura [Flickr]

    by Jorge Mir | 2 days ago | Read more

    xero79 posted a photo:

    jen-jorge-laura

    267263058_697bb42884_m Deploying Sinatra on DreamHost - Internal Server Error with views

    by Christopher Shea | 2 days ago | Read more

    I’ve been playing around with Sinatra (it’s awesome!) and thought I’d deploy something to my mess-around DreamHost account. I followed these instructions which totally worked and was so easy. But when it came time to actually deploy my real app with real views, I got nothing but “Internal Server Error”. Internal Server Error is not very [...]

    Rakefile toujours…

    by Gregoire Lejeune | 2 days ago | Read more

    J’ai fait quelques corrections dans les taches Rake pour les applications Bivouac. Cela fonctionne plutôt pas mal, et je vais donc pouvoir penser à passer cette version en phase de tests. Pour cela je vais me pencher sur la réécriture des exemples. De plus, comme Camping à l’air de dormir un peu dans son repository, [...]

    Nolan_eakins_2007 Two simple web businesses (via Google Reader)

    by Nolan Eakins | 2 days ago | Read more

    Google Reader shared an item on Google Reader

    Photo Readable test names in Rails 2.1

    by Hongli Lai | 2 days ago | Read more

    I’m currently working on a Rails application. It has some non-trivial business rules, so I ended up writing test methods along the lines of: Ruby def test_a_message_with_a_password_protected_channel_as_recipient_will_be_delivered_to_a_users_mailbox_if_that_user_is_subscribed_to_said_channel Okaaaay….. This is what I think of that method name: Nice boat! Other than the mental-psychological stress as well as an unexplainable impending feeling of doom that such a long method [...]

    Hospedagem gratuita para domínios .can.br

    by Roberto Bertó | 2 days ago | Read more

    Com a disponibilidade dos domínios .can.br para registro no Registro.br,a TeHospedo, em parceria com seus parceiros desenvolvedores de sites, está oferecendo hospedagem gratuita no plano Econômico para sites de candidatos as Eleições Municipais de 2008. O objetivo é apoiar os desenvolvedores de sites que tem site hospedado conosco e também apoiar a democracia brasileira unindo a [...]

    Balcony The Privacy Paradox

    by Patrick Curtain | 2 days ago | Read more

    Saw this /. article and read the Privacy Paradox from the NYT. In line with what I always thought; people don't really think about privacy and act openly. Until you mention privacy TO them.

    Hospedagem Rails agora com Passenger (mod_rails)

    by Roberto Bertó | 2 days ago | Read more

    No mês de julho iremos oferecer hospedagem gratuita para interessados em testar nossa plataforma Rails rodando Passenger. O Passenger é uma forma do Apache “falar” com o Ruby on Rails, outros “dialetos” usados são FastCGI, Mongrel e CGI. A TeHospedo pode suportar todos, mas atualmente está trabalhando mais com FastCGI e com Passenger. Interessados em testar o [...]

    Pixelhandler128 Happy Independence Day to the …

    by Bill Heaton | 2 days ago | Read more

    Happy Independence Day to the USA, show your colors: http://tinyurl.com/USflag

    Ryan-orange-large Alright quad-shot Americano… it’s just you me and this project. A little help, please?...

    by Ryan L. Cross | 2 days ago | Read more

    Alright quad-shot Americano… it’s just you me and this project. A little help, please? kthxbai.

    Hash-ment mieux…

    by Gregoire Lejeune | 2 days ago | Read more

    class Hash   def <<(h);h.each{|k,v|self[k]=v};end   alias :to_str :to_s   def to_s;"{"+self.map{|k,v|k.inspect+" => "+v.inspect}.join(‘, ‘)+"}";end end

    Future Places

    by Pedro Custódio | 2 days ago | Read more

    Ajánló: Rails blog kezdőknek

    by Ferenc Fekete | 2 days ago | Read more

    Bár ezen a blogon a hírek mellett inkább “advancedebb” témákkal foglalkozunk az ide tévedő, rails-el most ismerkedő látogatóknak hasznos lehet Pepusz blogja, amely mostanában indult és célja a keretrendszer népszerűsítése.

    Svg Viewer Demo

    by Tiago Cardoso | 2 days ago | Read more

    We are still working on the new editor for both InputDraw and Comics Sketch. Here is a short demo of the current state of the SVG Viewer. It still has its glitches and bugs.. and not every Svg will load, but we are getting there. But more important than the svg viewing capabilities  is the draw [...]

    Wormhole: Let's Communicate Between Caller and Callee

    by Genki Takiuchi | 2 days ago | Read more

    I made a small utility library named Wormhole. The library enables us to communicat<wbr />e between caller and callee.

    Here is a simple example of use.

       1  require 'rubygems'
       2  require 'wormhole'
       3  
       4  def foo(array)
       5    array << :foo # (1)
       6    Wormhole.throw array
       7    array << :baz # (3)
       8  end
       9  
      10  result = Wormhole.catch do
      11    foo []
      12  end.return do |array|
      13    array << :bar # (2)
      14  end
      15  puts result.inspect # => [:foo, :bar, :baz]
    

    First, the block passed to Wormhole.c<wbr />atch, the caller, is evaluated.<wbr /> The foo method, the callee, throw an array object passing through the wormhole. Then the array is caught by the last block passed to a return method. A block parameter of the block is the array. Finally, the process goes back to the point 3 after the last block ends. A return value of the foo method is returned via the return method.

    By using this utility, you can participat<wbr />e to a depth of a complicate<wbr />d system from a safer position.

    At the end, you can install this utility from the GitHub by using gem command like this.

       1  % sudo gem sources -a http://gem<wbr />s.github.c<wbr />om
       2  % sudo gem install genki-worm<wbr />hole
    

    Have fun!



    Tell us what you think of the new BlogSphere feature. We are continually looking to improve and update the functionality based on your feedback.

    Job Board

    Job Boards
    Find your next Ruby on Rails project or job.
    Exclusive content, regularly updated - onsite and tele-working positions listed.

    View the opportunities

    Latest from the Weblog

    Recent Recommendation

    Jerry Kiely:

    Frighteningly intelligent, hilarious, and a good cook

    - Sbubble S.Q, Ireland