To add Sam Vermette’s
SVPullToRefresh to your RubyMotion project:
- Add the SVPullToRefresh pod
- Add the Quartz Framework
|
|
# In your Rakefile
Motion::Project::App.setup do |app|
# ...
app.frameworks += ['QuartzCore']
app.pods do
pod 'SVPullToRefresh'
# ...
end
end |
Then – in your controller
|
|
def viewDidLoad
# ....
tableView.addPullToRefreshWithActionHandler Proc.new {
loadMagicalData(tableView)
# do some other magic
# then don't forget to:
tableView.pullToRefreshView.stopAnimating
}
# ...
end |
Posted in Ruby, RubyMotion.
NUI is an open-source library that allows you to style your iOS applications using CSS-like files and syntax. In my opinion, NUI carries few benefits over its commercial, KickStart backed, competitor
Pixate. First; NUI allows you to style your application on the fly while it’s running in the simulator. And Second; NUI styled-elements are not masked/wrapped in their special classes (like those PX* classes with pixate), rather, they remain as their original iOS declarations. The second point makes debugging the simulated application and tracking ons-creen objects (using cmd-hover) much easier.
Installation:
In your RubyMotion application’s Rakefile:
|
|
Motion::Project::App.setup do |app|
#...
app.pods do
# ...
pod 'NUI'
end
end |
Then run
rake clean & rake
Usage:
Create a theme.nss file (which will include your application’s stylesheet). Then in your
app_delegate.rb
|
|
class AppDelegate
@@nui_settings = NUISettings.init
@@nui_settings.setAutoUpdatePath("/absolute/path/to/project/and/theme.nss")
def application(application, didFinishLaunchingWithOptions:launchOptions)
@nui = NUIAppearance.init
# ...
end
end |
Run
rake and check your application in the simulator. Now, any changes to the
theme.nss file will be reflected right away to the running application in the simulator.
Happy styling
Posted in iOS, Ruby, RubyMotion.
Last weekend, I sat through the two-day
Consultancy Masterlcass by
Brennan Dunn &
Obie Fernandez. Both Brennan and Obie have extensive experience building their own successful consultancy firms.
The class was insightful and full of those ‘from the trenches’ experiences. What was of significant value is the knowledge transparently shared by students and alumni. All of whom are of similar mindsets and are taking their steps in establishing their own names in the consultancy world. I look forward to being part of a great community.
Posted in Professional, Ruby.
Many times I’ve heard professionals talk and plan out building software applications. Great ideas they’d like seen implemented, and how it could make things better. Though might not seem obvious – software applications, at least the good, are never built.
Applications are grown.[1]
There’s quite the range of differences between building an application and growing one, but I’ll focus here on few main ones.
Building something is associated with a resulting rigid structure and components. It takes effort to put together, but once build – it’s static. All what’s left is usage, admiration & maintenance.
On the other hand, growing something is an organic process. It rarely stops. It requires a continuous labour of love. You can reap benefits but as you do, you always have to give back, care and nurture.
Growing is more appropriate to the act of developing software. Applications doesn’t (or shouldn’t) reach a static rigid state, they always benefit from continuous assessment, reevaluation and changes. They adjust to surroundings. They evolve, transform and get bigger (but not necessarily more complex).
So – next time you’re discussing new applications – try to see how close the word ‘growing’ is to everyone.
[1] I wish I could remember where first I heard that or who said it.
Posted in General, Professional.
By Tamer
November 9, 2012
Consider that we have two models;
Well and
SurveyPoint . A Well represent an oil/gas/water well, each with multiple SurveyPoints. A SurveyPoint represent the well’s coordinate at a certain depth.
|
|
class Well < ActiveRecord::Base
has_many :survey_points
end
class SurveyPoint < ActiveRecord::Base
belongs_to :well
end |
Say, we’d like to implement a filtration mechanism that allows us to query the wells – and for those set of wells we’d like to conditionally present the set of survey_points for those set of filtered wells.
A method ‘
Well.search‘ would returns the set of wells we’re interested in (
@wells )
Using the power of AREL chaining, we could then conditionally extract the SurveyPoints using the following:
|
|
def SurveyPoint.find_for_wells(wells)
scope.where(:well_id => wells.select(:id))
end |
This roughly translates into the query:
|
|
SELECT * FROM SURVEY_POINTS WHERE WELL_ID IN (SELECT ID FROM WELLS WHERE ....) |
The challenge here is that if both results is large, depending on the cardinality – the database engine might not be able to make use of defined indexes and the outer query might not be optimizable.
Instead – if we use pluck instead of select:
|
|
def self.find_for_wells(wells)
scope.where(:well_id => wells.pluck(:id))
end |
Rails would fire two queries instead of an inner one. Pluck would first extract the list of ids (val_1, val_2, …) in an array before passing it to the main query. This roughly translates into:
|
|
SELECT * FROM SURVEY_POINTS WHERE WELL_ID IN (val_1, val_2, val_3, ....) |
No inner query is used in that case and the main one is easy to optimize.
Posted in Ruby.
By Tamer
November 8, 2012
I’ve recently upgraded a JRuby/Rails application from JRuby 1.6.3 (1.8 compatibility mode) to 1.6.8 (1.9 mode). Everything was working out fine except for actions relying on internal CSV library (FasterCSV in 1.8 mode). The error
can't convert Hash into String was thrown as CSV tries to generate the csv string.
This had the hallmarks that the application was still under the 1.8 mode (after a deploy to tomcat). The following XML entry in web.xml was essential to enforce the 1.9 mode:
|
|
<context-param>
<param-name>jruby.compat.version</param-name>
<param-value>1.9</param-value>
</context-param> |
Posted in Java, Ruby.
By Tamer
November 8, 2012
Using JRuby with trinidad (developer mode) – I was intermittently getting this error. Apparently thrown as estimated_time for the transaction was returning nil. I was also having all sorts of other issues (undefined method `metric_name’ for nil:NilClass) with all newrelics action summaries.
To resolve (following suggestions on the trinidad google group):
|
|
# config/initializers/newrelic.rb
if defined?(JRUBY_VERSION) && Rails.env == "development"
require 'newrelic_rpm'
NewRelic::Agent.manual_start({:dispatcher => :trinidad, :agent_enabled => true})
end
# Gemfile
group :development do
gem 'newrelic_rpm', '3.3.0', :require => false
end |
According to Nick Sieger’s gist – “NewRelic isn’t detecting Trinidad at the moment” – Although I could see trinidad’s detection mechanism implemented in newrelic’s most recent (3.5.0.1)
I’ve tried it with more recent versions of newrelic – but it seems 3.3.0 is the most stable.
JRuby 1.6.8 (1.9 mode)
trinidad 1.4.4
newrelic_rpm 3.3.0
UPDATE:
Getting another error of
undefined method `first' for true:TrueClass. The error is apparently thrown if the “EXPLAIN” query has failed against the DB engine. Although – I got the transaction_tracing disabled with explain_enabled set to false – yet this release still attempts to fire the “EXPLAIN” against the DB.
Since I’m using the oracle_enhanced_adapter, the current newrelic “EXPLAIN” query wouldn’t work – hence an error is thrown. However, the error consumption by newrelic returns true rather than nil.
Changing
handle_exception_in_explain to return nil instead of the true fixes it.
|
|
def handle_exception_in_explain
yield
rescue Exception => e
begin
# guarantees no throw from explain_sql
NewRelic::Control.instance.log.error("Error getting query plan: #{e.message}")
NewRelic::Control.instance.log.debug(e.backtrace.join("\n"))
# UPDATE: Added to prevent issues when drilling down deep into SQL (explain not working)
nil
rescue Exception
# double exception. throw up your hands
end
end |
Posted in Java, Ruby, Web.
By Tamer
October 30, 2012
Rails streaming is a great feature that allows you to optimize on server resources when dealing with large generated content. However – it might be a bit tricky to validate and test in local development.
First off – a local server that supports streaming is required. The only one I could find was trinidad which is moving to the likely defacto for JRuby/Rails projects. Trinidad uses tomcat-core as it’s servlet container and server.
Then make sure you grab the latest jruby-rack resolving most recent issues (1.1.10 at the time of writing).
This StackOverflow answer, along with this guide offer a comprehensive support as to what options work with Rails version as well as some gotchas (newrelic, caching, haml, …).
For Rails 3.2.x – It boils down to assigning an object that responds to an each method call to the response_body of a controller’s action. However – this doesn’t allow you to set a :stream =>true where it explicitly tells Rails to stream the respons. To resolve that I opted to use a render call, with a passed option hash as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
# Controller
def streaming_action
@objs = MyObj.where(:foo => 'bar')
render :nothing => true, :stream => true #setting the response to stream while rendering nothing
self.response_body = Streamer.new(@objs) # the object responding to 'each' call
end
#models/streamer.rb
class Streamer
attr_accssor :objs
def initialize(objs)
@objs = objs
end
# all the magic
def each
yield "Some initial output for header"
@objs.each do |obj|
yield "#{obj.attr}\n"
end
end
end |
This works with the following releases:
JRuby 1.6.8
Rails 3.2.8
jruby-rack 1.1.10
trinidad 1.4.4
Posted in Ruby.
By Tamer
October 23, 2012
I came across the requirement of updating a page element from the result of an Autocomplete. The server results were to be placed in a select element as set of option items.
I had to overwrite some
JQuery UI Autocomplete private methods as apparently there was no easy way of generating HTML and embedding it in the right spot on the page:
The JSON server response:
|
|
[{"id":"aaa","id_and_ba_name":"bbb"}, ...] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
var auto = $("#lc").autocomplete({
minLength: 3,
delay: 600,
dataType: 'json',
source: '/remote/action',
open: function() {
$("ul.ui-autocomplete").remove(); //removes the ul styling for dropdown
}
})
auto.data("autocomplete")._renderMenu= function(element, items) {
//treats the DOM element as the menu where items are to be placed
var self = this;
$('#the_select_element').show().html('');
$.each( items, function( index, item ) {
self._renderItem($('#the_select_element'), item );
});
}
auto.data("autocomplete")._renderItem= function(element, item) {
// generate options elements and adds them to menu
return $("<option></option>")
.data("item.autocomplete",item)
.attr("value",item.id)
.append(item.id_and_ba_name)
.appendTo(element);
} |
JQuery 1.8.16
Rails 3.1
Posted in Ruby, Web.
By Tamer
December 6, 2011
JRuby 1.5.6 (I know. Old)
Rails 3.0.1
Polyglot 0.3.3
UPDATE: see easier fix below
Getting the following error when bundling:
|
|
Java::JavaLang::ArrayIndexOutOfBoundsException: An error occured while installing polyglot (0.3.3), and Bundler cannot continue.
Make sure that `gem install polyglot -v '0.3.3'` succeeds before bundling. |
JRuby YAML parser is erring with this version of Polyglot (don’t you love JRuby!!).
‘gem dependency -R polyglot’ will get you the reverse dependencies on the library. In this case it’s ‘treetop’
Had to edit the ‘gemspec’ files and restrict the version of polyglot to ‘< 0.3.3'
Example - From
s.add_runtime_dependency(%q
, [">= 0"])
To
s.add_runtime_dependency(%q, [">= 0", "< 0.3.3"])
Yak shaving!!!
UPDATE: EASIER FIX:
just use gem 'polyglot', '0.3.2' in your Gemfile, it might just do the trick.
Posted in Ruby.
By Tamer
November 17, 2011