Experienced web developer, rubyist and consultant.
I enjoy working in projects that value elegant design and best-practices, while providing good, flexible working conditions.
Interested in the exploratory nature of startups, agile methodologies and entrepreneurship - minus the bs.
Business analysis, product development, systems architecture and programming, project management
January '12 - March '12 - allocated to Coinvalores (brokerage firm). Stealth app development and tuning, consulting on planning and development processes.
December '11 - allocated to Bio-Ritmo (fitness chain), tuning their academy management apps for performance
September - November '11 - allocated to Editora Abril, working on their web publishing system backing their magazines' sites, and then on http://iba.com.br/, their digital subscription service.
August '11 - worked on last stretch of development and delivery of a high traffic web game for a major European client.
Development and deployment of Ruby on Rails APIs and admins for iOS applications, and baby-sitting them up on Heroku.
Participation on honing development processes and methodologies, pushing for the introduction of best-practices like TDD/BDD and outside-in development.
Development of software as a service (SaaS) apps and customization of open source apps for other businesses, using Ruby on Rails.
Development of a SaaS product targeting the Brazilian real-estate law market.
Consulting, implementation and customization of ecommerce, institutional websites of all sorts, and development of custom web applications.
Working at Columbia House online as a subcontractor.
Mockup slicing, HTML, CSS, Javascript coding. some Applescript, some Perl, some PHP as well.
Mockup slicing, HTML, CSS, Javascript coding, integration with Python and Vignette StoryServer backends.
When using poltergeist edge, I'm only able to access its methods when passing js: true to feature specs:
scenario "Worst case", js: true do
...
end
Though I now know scenario() is supposed to not need the js flag.
Also, without the js flag, all requests are sent asking for HTML, not JS. But with it, I get strange behavior - steps to login using devise don't work, user factories are seen as invalid...
My config:
require 'capybara/poltergeist'
Capybara.javascript_driver = :poltergeist
Also tried registering the driver:
require 'capybara/poltergeist'
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, { debug: true, js_errors: true })
end
Capybara.javascript_driver = :poltergeist
Does this make sense? Is this a bug, or am I missing something basic here?
I've opened an issue on the poltergeist Github project as well, and I'll post updates on it here, and vice-versa.
class Api::StoresController < ApplicationController
respond_to :json
def index
@stores = Store.all(:include => :products)
respond_with @stores
end
end
Returns only stores without their products, as does
Store.find(:all).to_json(:include => :products)
The association is tested, I can see the nested products in console ouput from, say,
Store.first.products
What's the correct way to get them products included with MongoMapper?
Here are my models:
class Store
include MongoMapper::Document
many :products, :foreign_key => :store_ids
end
class Product
include MongoMapper::Document
key :store_ids, Array, :typecast => 'ObjectId'
many :stores, :in => :store_ids
end
UPDATE
In trying Scott's suggestion, I've added the following to the Store model:
def self.all_including_nested
stores = []
Store.all.each do |store|
stores << store.to_hash
end
end
def to_hash
keys = self.key_names
hash = {}
keys.each{|k| hash[k] = self[k]}
hash[:products] = self.products
hash[:services] = self.services
hash
end
And in the controller:
def index
@stores = Store.all_including_nested
respond_with @stores
end
Which looks like it should work? Assuming the array of hashes would have #to_json called on it, and then the same would happen to each hash and each Product + Service. I'm reading through ActiveSupport::JSON's source, and so far that's what I've grokked from it.
But, not working yet... :(
Chargify has this Cucumber scenario in their docs.
Scenario: Retrieve a customer via my reference id (as an integer or simple string)
Given I have a customer with these attributes
| reference | first_name | last_name | email |
| 7890 | Joe | Blow | joe@example.com |
When I send a GET request to https://[@subdomain].chargify.com/customers/lookup.xml?reference=7890
Then the response status should be "200 OK"
And the response should be the xml:
"""
<?xml version="1.0" encoding="UTF-8"?>
<customer>
<id type="integer">`auto generated`</id>
<first_name>Joe</first_name>
<last_name>Blow</last_name>
<email>joe@example.com</email>
<organization>`your value`</organization>
<reference>7890</reference>
<created_at type="datetime">`auto generated`</created_at>
<updated_at type="datetime">`auto generated`</updated_at>
</customer>
"""
I'm trying to follow their approach in testing an API we're developing here, instead of checking for the tags one by one, like I we were doing before coming across this example.
So far no luck matching the response's output with the step's multiline string, due to formatting issues. Haven't found a way with Nokogiri nor with simple stripped string comparison.
Is there an elegant (and efficient) way to do this?
Update
Here's the cucumber step using Mark's solution:
Then /^I should see the following output$/ do |xml_output|
response = Hash.from_xml(page.body)
expected = Hash.from_xml(xml_output)
expected.diff(response).should == {}
end
I'm working on a micro-forum of sorts, whereby a quick (close to tweet-size) topic message is posted by a special user, which subscribers can respond to with like-sized messages of their own. Straightforward, no 'digging' or voting of any sort, just a chronological flow of responses for each topic message. But with high traffic expected.
We would like to flag topic messages according to the response buzz they atract, using a scale of 0 to 10.
Been googling for trend algorithms and open source community application examples for a while, and so far have gleaned two interesting references, which I don't fully grok yet:
Understanding algorithms for measuring trends, a discussion on comparing wikipedia pageviews using the Baseline Trend Algorithm, here on SO.
The Britney Spears Problem, an in-depth article on how to rank search terms, while processing large streams of data.
From the first I understand the need to check the slope in activity, and to balance the weight between two items that differ greatly in scale of activity. But how do I compare many items, growing in number quickly across time? And then, how do I break the items within "buzz grades" from 0 to 10?
The second reference is fascinating, but over my head at this point. From a first pass I've understood the need to keep memory usage stable while keeping counters and storing references to items if necessary. But I haven't figured a fitting algorithm for my specific use case from it, yet.
It's worth noting that I come from a non-computer-science and definitely non-statistics background. Please bear with me :) Any help and code samples (specially in Ruby) would be greatly appreciated.
We have a Rails app with a view that gets populated with data from a third-party API. Currently, this view uses a swf streamer to open a socket to the endpoints.
Recently, the API's provider has asked us to switch to long polling ajax calls, and to pipe requests through a proxy in our server.
We're considering using node-http-proxy, to take advantage of node's speed and concurrency handling in case we get high traffic. We're new to Node.js, though.
The other option we're looking at is using the Rails app itself to forward these requests, the advantage being that we could use the existing session handling.
We'd prefer to use node-http-proxy, as it seems the most elegant solution (and an opportunity to play with Node.js, of course ;), but haven't figured out how to integrate it with our app's sessions (activerecord session store on postgres).
Is there a way to do it? Are there any other auth/security/session-checking strategies using node-http-proxy in parallel with a Rails app?
Oliver
I want to get autotest to run Steak acceptance tests whenever one of my rails app's relevant files is changed. After studying Rspec's and Cucumber's own autotest configs, I'm trying the following mappings:
Autotest.add_hook :initialize do |at|
at.add_mapping(%r%^spec/acceptance/.*_spec.rb$%, true) { |filename, _|
filename
}
at.add_mapping(%r%^app/(models|controllers|helpers|lib)/.*rb$%) {
at.files_matching %r%^spec/acceptance/.*_spec.rb$%
}
at.add_mapping(%r%^app/views/(.*)/.*rb$%) {
at.files_matching %r%^spec/acceptance/.*_spec.rb$%
}
end
the first one works: whenever a Steak spec is changed, it gets run again.
but the second and third don't. changing any source files under the /app subdirectories just gets ignored.
what's the correct way to get these mappings to work?
thanks Oliver
How do I check the "Please fill out this field" message that appears above required fields when they're submitted empty?
Right now my cucumber scenario seems to ignore the empty field completely, submitting the form successfully.
(I'm validating the fields presence, and when submitting manually, the form does show the message)
We're using God to monitor our server processes, and were wondering if we should use something like Monit to make sure God gets up if something unexpected happens.
A quis custodiet ipsos custodes? conundrum :)
Googling for it didn't bring any mentions of this being done, which makes me think it's probably pretty rare.
Has anybody here seen a need for it?
Looks like this version has been pulled from Rubygems, only beta.12 and beta.13 are listed:
http://rubygems.org/gems/sprockets
So you'd need to get the specific beta.2 branch from the repo, as Thariq suggests.
BUT, I'd probably go for one of the versions listed on rubygems - there must be good a reason why they were pulled ;)
How do I stub an http request, like this one to the twitter api below, on a global scope so it's valid for all tests in a Test::Unit suite?
stub_request(:get, "https://api.twitter.com/1/users/show.json?screen_name=digiberber").
with(:headers => {'Accept'=>'application/json', 'User-Agent'=>'Twitter Ruby Gem 1.1.2'}).
to_return(:status => 200, :body => "", :headers => {})
This WebMock stub works within a TestCase subclass's setup() block, like
class MyTest < ActiveSupport::TestCase
setup do
stub_request(...)...
end
end
But doesn't get recognized if I put it within a global setup in TestCase itself:
require 'webmock/test_unit'
class ActiveSupport::TestCase
setup do
stub_request(...)
end
end
Which gives me the error:
NoMethodError: undefined method `stub_request' for ActiveSupport::TestCase:Class
I've also tried by patching the method def itself
def self.setup
stub_request(...)
end
but it doesn't work either.
Something similar happens when I use FlexMock instead of WebMock. Seems to be a scope problem, but I can't figure out how to go around it. Ideas?
This post on different ways to setup() and teardown() led me to just do
class ActiveSupport::TestCase
def setup
stub_request(...)
end
end
hadn't thought of declaring it as an instance method. :P
When iterating results, you can store them in model objects, which in turn map to tables in sql databases (mysql, postgres, oracle), or documents in nosql dbs like mongodb.
Tweaking an example in the twitter gem's README:
# Find and store the 3 most recent marriage proposals to @justinbieber
Twitter::Search.new.containing("marry me").to("justinbieber").result_type("recent").per_page(3).each do |r|
MyLocalTweetModel.create!(:from_user => r.from_user, :text => #{r.text}")
end
This can be done with any database, really.
The decision over which database to use depends on many other factors, such as where your app will be hosted, what traffic you expect, how you plan to scale it... and taste is definitely one of these factors, and not an unimportant one. I hate Active Record migrations, for instance, though I like its many other niceties. Active Record is the default ORM rails uses for sql databases.
If you're new to all this, just start on a simple sqlite database with Active Record. There's more of a learning-curve to the alternatives.
This discussion on the rails-i18n google group has an interesting solution:
#in a locale file
en:
education_levels:
gcses: Some GCSEs or less
collegeA: College A levels
some_university: Some University, no degree
bachelors: University graduate - Bachelors or equivalent
masters: Masters degree
professional: Professional Degree
doctorate: Doctorate
#And in a model:
class Education < ActiveRecord::Base
def translated_education_level
I18n.t(education_level, :scope => :education_levels)
end
end
#In a helper:
module EducationHelper
def education_levels
I18n.t(:education_levels).map { |key, value| [ value, key ] }
end
end
#And then in your view:
<%= f.select :education_level, education_levels %>
In the comments to the solution for How do I find an image on a page with Cucumber/Capybara, somebody asked:
I can't seem to figure how to get this to work with URLs generated by Dragonfly. They look like this: /media/BAh_some_long_string_AwIw/12_11_52_810_5x5.jpg?s=7e360000, where 5x5.jpg is my file name. I've tried something like: //img[@src="/media//#{image}?s=*"] but it doesn't work. Got any tips? – Ramon Tayag Feb 25 at 4:18
I have a similar problem, only worse - in my case, the generated image paths don't even include a (jpg|png|gif) file name, they only have these really long ids:
<img src="/media/BAhbB1sHOgZmSSIdNGQ4MTEyOGU3ZjViZmQwZTQ4MDAwMDAyBjoGRVRbCDoGcDoKdGh1bWJJIg0yMDB4MjAwIwY7BlQ" />
(Using dragonfly with mongo/gridfs)
These paths get rendered alright, but I can't figure out how to find them in a Cucumber/Capybara step :P
Any ideas? I looked at the Dragonfly's features, but they only test the rendering of the image itself, without detecting it's existence within an html page.
Answering my own question, after talking to Dragonfly's author (he's working on making this easier):
#route
match '/media/:dragonfly/:file_name', :to => Dragonfly[:images]
#model
class Store
include MongoMapper::Document
key :photo_uid, String
key :photo_name, String
image_accessor :photo
end
#view
<%= image_tag @store.photo.thumb('274x207#').url(:suffix => "/#{@store.photo_name}") if @store.photo %>
#cucumber
Then I should see the image "my_photo.png"
Then /^I should see the image "(.+)"$/ do |image|
page.should have_xpath("//img[contains(@src, \"#{image}\")]")
end
The key is adding an [attachment]_name field to the model, which Dragonfly populates automatically, and then passing it on as a suffix to url(). And the routes needs to allow for a :file_name param besides the generated dragonfly identifier.
Say I have a formtastic form that creates a Store and allows selection of Services it provides:
<%= semantic_form_for @store do |f| %>
<%= f.inputs :services, :as => :check_boxes, :collection => Service.all %>
<%= f.buttons %>
<% end -%>
I want to allow the user to add a new Service in case he doesn't see it in the options, right from the form.
There are many examples for simple nested form element addition, say of a Task entry to a Project, and even a gem that helps with this, but I haven't found any that create a new resource so it'll show as part os checkbox or select options.
Got it working this way:
<%= semantic_form_for @store do |f| %>
<%= f.inputs :services, :as => :check_boxes,
:collection => Service.all,
:wrapper_html => { :id => 'service_fields' } %>
<%= f.buttons %>
<% end -%>
Added an id to the parent list item around the checkbox field listing, so it can be accessed by this js after submitting a text field with the new service name:
<input type="text" id="new_service_name" />
<input type="button" value="ok" id="btnSave" />
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
$.ajax({
url: '/admin/services.json',
type: 'POST',
dataType: 'json',
data: 'service[name]=' + $('#new_service_name').val(),
success: function(data) {
addCheckbox(data);
}
});
});
});
function addCheckbox(name) {
var container = $('#service_fields fieldset ol');
var inputs = container.find('input');
var id = inputs.length+1;
//var html = '<input type="checkbox" id="cb'+id+'" value="'+name+'" /> <label for="cb'+id+'">'+name+'</label>';
var html = '<li><label for="store_services_'+id+'"><input id="store_services_'+id+'" name="store[services][]" type="checkbox" value="'+id+'" />'+name+'</label></li>';
container.append($(html));
}
</script>
Then, in ServicesController:
class ServicesController < ApplicationController
respond_to :json
def create
service = Service.create!(params[:service])
respond_with(service)
end
end
The following formtastic form checkbox field set:
<%= semantic_form_for @store do |f| %>
<%= f.inputs do %>
<%= f.input :services, :as => :check_boxes, :collection => Service.all %>
<% end -%>
<% end -%>
is sending bad params for :services on a Cucumber test using Capybara, making the test fail, while the actual app sends the correct ones, which gets processed fine:
#cucumber steps using the boiler_plate capybara web_steps.rb:
Given a "Mail Order" service
...(steps for rest of the form)...
When I check "Mail Order"
And I press "Create Store"
Then I should see "Store was successfully created."
And I should see "Mail Order"
#params sent by cucumber
"store"=>{"services"=>["[\"4d8247ed7f5bfd2275000004\"]"]
#params sent by app on manual test
"store"=>{"services"=>["4d8247ed7f5bfd2275000004"]}
Though the html form itself is rendered the same way in both cases:
<input id="store_services_4d8247ed7f5bfd2275000004" name="store[services][]" type="checkbox" value="4d8247ed7f5bfd2275000004" />
Seems like somewhere during the request params-building, the form key/value pairs for that field get parsed differently when submitted by Cucumber/Capybara.
Anyone else come across this?
Answering my own question:
Got a pointer from Capybara's author, Jonas Nicklas, that led me to this rack-test patch which hasn't been committed yet
For now I'm just using the fork and branch where the patch lives:
gem 'rack-test', :git => 'https://github.com/econsultancy/rack-test.git', :branch => 'econsultancy-20110119'
And that does the trick. I imagine this patch will be merged in very soon though, as it was submitted a couple of months ago.
I need to make a site's menu navigate like OSX's Finder in column view, where each level appears next to its parent in a vertical column.
Have been googling this for a couple of hours now, and this Jquery plugin seems to be the closest match (There's a demo here)
From a first trial, it seems somewhat hard to customize. I need it to behave and look differently in a couple of ways:
Does anybody know how to accomplish these with this plugin, or could point me towards simpler implementations that are closer to these specs?
Here's the menu html structure:
<ul id="nav">
<li class="current" id="nav-o-que-estamos-fazendo">
<a href="/o-que-estamos-fazendo/">O que estamos fazendo</a>
<ul id="nav-o-que-estamos-fazendo-children">
<li id="nav-o-que-estamos-fazendo-children-ficcao">
<a href="/o-que-estamos-fazendo/ficcao/">Ficção</a>
</li>
<li class="current" id="nav-o-que-estamos-fazendo-children-documentario">
<a href="/o-que-estamos-fazendo/documentario/">Documentário</a>
<ul id="nav-o-que-estamos-fazendo-children-documentario-children">
<li class="current" id="nav-o-que-estamos-fazendo-children-documentario-children-josephine-king">
<a href="/o-que-estamos-fazendo/documentario/josephine-king/">Josephine King</a>
</li>
</ul>
</li>
<li id="nav-o-que-estamos-fazendo-children-televiso">
<a href="/o-que-estamos-fazendo/televiso/">Televisão</a>
</li>
<li id="nav-o-que-estamos-fazendo-children-museus">
<a href="/o-que-estamos-fazendo/museus/">Museus</a>
</li>
</ul>
</li>
<li id="nav-o-que-ja-fizemos">
<a href="/o-que-ja-fizemos/">O que já fizemos</a>
</li>
<li id="nav-o-que-somos">
<a href="/o-que-somos/">O que somos</a>
</li>
<li id="nav-quem-somos-contato">
<a href="/quem-somos-contato/">Quem somos | contato</a>
</li>
<li id="nav-mirabolancias">
<a href="/mirabolancias/">Mirabolâncias</a>
</li>
</ul>
As generated by the 'nav' liquid tag on Harmonyapp)
With the following Store and Service models, managed with MongoMapper:
class Store
include MongoMapper::Document
key :service_ids, Array, :typecast => 'ObjectId'
many :services, :in => :service_ids
end
class Service
include MongoMapper::Document
key :name, String
many :stores, :foreign_key => :service_ids
end
I have this form, done with Formtastic:
<%= semantic_form_for @store, :url => admin_store_path(@store), :method => :put do |form| %>
<%= form.input :service_ids, :label => "Select Store Services",
:as => :check_boxes,
:collection => Service.all %>
<% end -%>
The controller uses Inherited Resources, and the edit action is implicit.
When editing a @store with services already associated with it, the checkboxes for the latter don't show as checked.
Formtastic's README warns it doesn't support MongoMapper officially, but it also says people have been using both together successfully, and I've seen some examples of this online.
I suspect Inherited Resources also doesn't support it, from what I've seen from Devise + Simple Form, both from the same authors and which don't support MM. They're working towards using an ORM adapter in their gems, but it isn't ready yet AFAIK.
And I've had problems with it already, I'm overriding the update action to get it to work:
def update
store = Store.find(params[:id])
if store.update_attributes!(params[:store])
flash[:notice] = 'Store was successfully updated.'
redirect_to admin_store_path(store)
else
redirect_to new_store_path
end
end
Does anybody know where the conflict with MM is, either in Formtastic or IR, and a hack just to get these checkboxes checking?
From reading the db:test tasks's source, it looks like they only care about grabbing the test db info from database.yml, but don't care which actual environment they're doing it under.
You might need to run rake db:test:prepare RAILS_ENV=test to ensure you're under the test environment.
One way might be to dump the dev data to yaml (this plugin does that and there are probably others that will do the trick), and then use db/seeds.rb to write a script loading its contents and using rails models to recreate them on the production db with rake db:seed
rake db:seed won't hose your data (it just loads db/seeds.rb, see the source here and here), but be sure to backup your data before anything :)
I'd suggest playing with a sandbox app and db clone before going ahead and running this on production.
Try
ActiveResource::Base.include_root_in_json = false
If you need to keep the top root and just remove the associated credit card object's root, then you might need to customize the json output with #to_json, like this:
def to_json(options = {})
{ "user"=>
{"credit_card"=>
{"number"=> self.credit_card.number }
},
"user_name"=> self.user_name
}.to_json(options)
end
From that picture, I'm understanding you just want to exclude them from the coverage analysis?
If so, something like this might help:
http://psixty.wordpress.com/2010/06/22/how-to-exclude-files-in-rcova-code-coverage-tool-in-ruby/
I'd suggest using uploading a fixture image, as per this other SO thread
One way would be to avoid hitting the API at all, by faking the responses with Fakeweb
This will speed up your tests :) And decoupling them from external services is a Good Thing in general - saves bandwidth, ensures your tests will run if the service is down, etc
snapshot is set as a local variable in controller, so the template doesn't see it. Set it as an instance variable:
@snapshot = Snapshot.find(params[:id])
then in the template:
:locals => {:snapshot => @snapshot
Are there any implementations (open source or proprietary) of TinyMCE-like widgets for iOS apps?
If not, are there any references, tutorials, recipes etc no how to roll one's own?
Try
<% if f.object.is_white == true %>
Seem to remember you could access the object this way (not 100% sure though ;)
@JoãoPintoJerónimo 60 days
is Api::LoginController being described higher up on the describe chain? I wonder if ActionController::TestCase::Behavior is being mixed in. can you access controller.session?
what doesn't work exactly? is the session helper not working at all, or just is it that session[:msg] isn't set? what does session.inspect give you?
@Tonys there is, and when submitting manually the message appears.
@AndyWaite the default, from looking at the capybara README just now it looks like it's :rack_test. and it doesn't support javascript, which I didn't expect. so the answer would be to use a js driver?
makes sense. so upstart would be closer to the core than using service?
I see many questions about deployment on stackoverflow (like this one), and it's a common task for rails devs. Perhaps this is a question that belongs on both?
None of the three answers work for you?
it'd be good to see the routes + controller
It depends, are you testing an interface of an html editor? if so, it could be correct ;)
...I mean I'm just adding the stub call in the wrong place, where the mocking libs don't get recognized. I can't figure out where the correct place would be, or how to force the inclusion of those stubbing/mocking methods there. Tried FlexMock.flexmock(), for instance, just but Flexmock module just isn't there, though it's required (tried include()ing it, but no luck either)
@Wizard of Ogz, actually that was my original approach - stubbing twitter gem's Twitter.user() with flexmock under global setup(). But flexmock() also doesn't get recognized :P. I think in both approaches I'm just stubbing in the wrong place, but can't figure out the correct one
wouldn't fakeweb have the same issue? register_uri() is very similar to webmock's stub_request(), and I'd need to run it globally as well
it returns Hashie::Mash objects