Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

Friday, October 12, 2012

RoR Double Clutch

This is a pattern have implemented in three different projects of mine, so I'm writting it down once and for all the next times I wrap my head arround this until I remember I have already have done it.

In the Dezquare project, the users are offered a game that helps them in finding a sutable designer. The game varies accorging to all sorts of conditions. The sequence is broken down into a series of basic elements that can be manipulated and tweeked from an admin consule.

The aim is to have an implementor grabbed from the database and react to a particular context as part of a user flow sequance





The players:

  • A controller
  • A context object (as an ActiveRecord)
  • A referenced implementor descriptor (as an ActiveRecord)
  • An implementor

The sequence:

  1. The controller identifies the context object and passes the request params
  2. The context object finds its implementor descriptor and passes itself as an argument
  3. The implementor descriptor converts its implementor class name field into an entity (imp.camelize.constantize)
  4. The implementor descriptor invokes on the implementor method with the context object and its own agruments field (if applicable)

The code 

Note: this code will not work by itself. its only expressing the idea
The standard controller answering a play request
def play
    @game=Game.find(session[:game_id])
    @results = @game.set(params)
end

The context object (Game), persistant and stateful, belongs to a "stage" and passes the request and context
def set(params)
    self.stage.set(self,params)
end

The implementor descriptor (Stage), persisted common object, known here as the "stage" generated an entity and calls it.
def klass
    self.imp.camelize.constantize
end

def set(game,params)
    klass.set(game,params,self.arguments)
end

The implementor (name derived from a data field), unpersisted, statless entity, acts upon the context it is given and returns the results
def self.set(game,params,arguments)
    #pay dirt
end




Wednesday, August 1, 2012

Wikisrains moves to Public Beta phase

Months of hard work have finally resulted in airing the WikiBrains machine learning engine.
Having people using it is so exiting, since as more of them do, the smarted it gets.

Although one would need to register to actually use the brainstorm GUI tool, its easy to see the daily increase in vocabulary and context just by going into the search page and checking out 'Apple' (just an example).

Each time a user lines up a couple of words, may they be of his own design or using existing connections from the suggestion list, the brain is enriched by a new synapse.

The wiki engine uses a graph database to store the words as objective points and the subjective links between them are what people have to say about those words.

We still have several usability issues with the GUI, perhaps too cumbersome one may argue. but despite some snags on the way, it works (which makes me really happy). No performance issues so far, and the user base is steadily growing.

Thumbs up for the Wikibrains team!






.

Tuesday, April 10, 2012

Titanium for Android and RoR

Lately, I've been playing around with the Titanium IDE for mobile development.
Its pretty nice once you get a hang of it.
My first application (code name Moris) I made to communicate as a mobile front end for the Gizmo server.

It came out rather simple since my API on the server side are aleady set to spit out JSON structures.



I've found that the simplest way is as following:
First I created a generic send function with a global client object:



var SERVER = 'https://YOUR-DOMAIN/api/';


var send = function (action, data, resFunc){
client.open("POST", SERVER+action);
  if (resFunc!=null) {
  client.setOnload(resFunc);
  };
  client.send(data);
}


var client = Ti.Network.createHTTPClient({
     onload : function(e) {
         alert('success '+this.responseText);
     },
     onerror : function(e) {
         alert('error');
     },
     timeout : 5000  /* in milliseconds */
 });


Then I add a specific function for each API I'd like to call on the server:


exports.login = function(user,pwd) {
send("login", {mail:user, password:pwd}, function(e) {
         //alert(this.responseData);
        Ti.App.fireEvent("gizmo_login_complete", JSON.parse(this.responseText));
     });
};


exports.userInfo = function(resultFunction) {
send("user_info", {data:null}, resultFunction);
};


In these two examples, I've Pass a function that would handle the particular case of returned data.
For the login, I fire a Titanium event that is caught on the app.js while for the user info I inject the function each I do the call.




Thursday, March 1, 2012

Installing RoR 3.x on Ubuntu 10.4 with MySQL

I'm writing this as a reminder for myself.
To install Rails (3.x) on Ubuntu 10.4 with a MySQL gem do the following:


sudo su
apt-get install build-essential
apt-get install ruby rdoc libopenssl-ruby
wget http://production.cf.rubygems.org/rubygems/rubygems-1.3.7.tgz
tar zxvf rubygems-1.3.7.tgz
cd rubygems-1.3.7
ruby setup.rb
ln -s /usr/bin/gem1.8 /usr/local/bin/gem
sudo apt-get install ruby1.8-dev
gem install rails

To install the MySQL gem: 

apt-get install ruby-dev libmysql-ruby libmysqlclient-dev
gem install mysql


After creating the application using
rails new myApplicationName -d mysql
Running the rake db:migrate will result in error, since it requires a JS engine.
To fix that, edit the Gemfile in the application directory and add the following lines:


gem 'execjs'
gem 'therubyracer'

and then run
bundle install

* Another option is to install NodeJS on the machine, as the javascript engine by following these steps:
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs npm
.

Sunday, October 16, 2011

Mysql2::Error (Invalid date: xx) on a text field?!

I have this rule, the longer it takes to figure out a bug, the dumber the solution is going to be. This one was no exception.This bug on the rails adapter for mysql (the native Mysql2 for Windows) cost me a day and a half of bewilderment.


The symptoms were that when populating a particular field in a table caused the created_at filed that was directly after to corrupt.
Although the entry would save successfully, once i tried to retrieve it, it would omit an argument error, without  any explanations  or indication to the field that was causing the problem.

After literally hours spent reinstalling and reconfiguring and redeploying my application and the run times involves i stumbled upon this error "Mysql2::Error (Invalid date: xx)" where xx was the text value of the field preceding the "created_at" standard field.
A quick search on Google pointed me to the bug in Mysql2.

My solution was (cross my heart and hope to die) was to add an extra field that i never populate before the date fields.

Good Luck.


Thursday, August 11, 2011

Ruby 1.8.7 CSV parser workaround

Apparently there is some kind of problem when using the CSV parser for particular text structures. I want able to determine the exact cause of this problem expect that for some csv structures, the parse process result in an error.

In my frustration I resorted to write my one parser that is implemented as following:

 def self.parse(text)
    rows=text.split("\r")
    res=[]
    rows.each{|row|
      res << row.split(",")
    }
    res
  end

And amazingly enough, that's what did the trick.

Independent on Sundays.




Thursday, April 21, 2011

Ruby rufus-scheduler on Rails

I've been playing around with the rufus-scheduler, trying to make it work in a rails environment.
The problem I was facing was that the new threads that were created by the scheduler for running the jobs were somehow detached from the the Active Record environment resulting in a failure to load my application models within their scope.

Every time I tried loading a model object from the database I would get an error that the copy of my job instance "has been removed from the module tree but is still active"

Pretty confusing

My cowboy programming solution for this was to activate a block as the job instance and in it invoke a controller. from the controller, I managed to access everything I needed in terms of active support.

The code as following:

scheduler.every "10s" , :timeout => "1m", :tags => "etl_job" do |job|
  url = "#{server_url}?tag=#{job.params[:tags]}"
  run(url)
end
The run is defined as:
def self.run(url)
    logger.debug "--- Initiating Job with:  #{url} "
    uri = URI.parse(url)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true if uri.scheme == 'https'
    request = Net::HTTP::Get.new(uri.request_uri)
    response = http.request(request)
  end
The url hits a controller and from there everything acts normally for rails.

Independent on Sundays

Sunday, October 31, 2010

Rails Application variable

It almost seemed that there was no easy way out of putting application scope variables in the database.
But there is a way out:
    if Thread.main[:uuid] == nil
      Thread.main[:uuid]=0
    end
    uid = Thread.main[:uuid] += 1


This code accesses the mail thread of the rails process and puts a variable on it. (the thread is an object and can have key => value sets)
And since rails has only one main thread... its shared with all the threads underneath.

Good Luck

Sunday, October 24, 2010

AAdmin - Flex on Rails Agile Admin Application

The AAdmin is a little project I'm developing on the side, for Valueshine which in essence is a fast Administration Application based on a Ruby on Rails back-end and a Flex Web front-end.

I love fast development mainly because I'm a lazy son of a batch file and for some reason, I feel that Ruby and Rails was made just for people like me.

Having a server side application that 70% of its tasks sum up to persistence functionality just screamed scaffolding to me. the only obvious difference is that for the sake of using a flex client, i would have to skip over the default view machinery, that are generated by the rails scaffold.

Pre Programming:
I've created the alternative controller template so scaffolding command would generate an XML based web service.
to match that I've written an ActionScript client side that talks CRUD on the one side and hands out a set of a-sync methods on the other side.

The application, is based on the two elements described above, let me have a RoR restful web services that would accommodate a rich client.

The server:
I have employed a standard scaffold script generation with a tweak to the controller template. this change bypasses the standard view that is created by Rails to relay on pure XML rendering.
there is one extra controller that is utilized for configuration data purpose. I use it for authentication, and to extract the entities structure xml file.

The Client:
This part is where the quick admin app comes to play. the AAdmin client enables all CRUD functionality on a list of entities, predefined in an entity xml.
the client logs in, extracts the entity xml file, and presents the table structure and functionality according to the definitional in the file.

Screen shoots:
AAdmin Login Screen.

The CRUD Data View

The Create and Edit screen















Resources:

Wednesday, October 20, 2010

Flex for Rails Scaffolding (cont) - the controller template

I've made a little improvement  to my development process, in such a way that the scaffolding i do for creating the web services I later use for my flex client are generated in their final form without the need to adjust them.
What i did was make some changes to the controller scaffold template.
The controller.rb template file is located at: [Ruby Home]\lib\ruby\gems\1.8\gems\rails-2.3.4\lib\rails_generator\generators\components\scaffold\templates

Backup the original (or pick it up from here).
Download the modified template


The Template should end up looking like:

class <%= controller_class_name %>Controller < ApplicationController
  # GET /<%= table_name %>
  # GET /<%= table_name %>.xml
  def index
    @<%= file_name %> = <%= class_name %>.all
   render :xml => @<%= file_name %>
  end

  # GET /<%= table_name %>/1
  # GET /<%= table_name %>/1.xml
  def show
    @<%= file_name %> = <%= class_name %>.find(params[:id])
    render :xml => @<%= file_name %>
  end

  # GET /<%= table_name %>/new
  # GET /<%= table_name %>/new.xml
  def new
   @<%= file_name %> = <%= class_name %>.new
   render :xml => @<%= file_name %>
  end

  # GET /<%= table_name %>/1/edit
  def edit
    @<%= file_name %> = <%= class_name %>.find(params[:id])
   render :xml => @<%= file_name %>
  end

  # POST /<%= table_name %>
  # POST /<%= table_name %>.xml
  def create
    @<%= file_name %> = <%= class_name %>.new(params[:<%= file_name %>])
    if @<%= file_name %>.save
      render :xml => {:notice => '<%= class_name %> was successfully created.'}
    else
      render :xml => {:notice => @<%= file_name %>.errors}
    end
  end

  # PUT /<%= table_name %>/1
  # PUT /<%= table_name %>/1.xml
  def update
    @<%= file_name %> = <%= class_name %>.find(params[:id])

    if <%= file_name %>.update_attributes(params[:<%= file_name %>])
      render :xml => {:notice => '<%= class_name %> was successfully updated.'}
    else
      render :xml => {:notice => @<%= file_name %>.errors}
    end
  end

  # DELETE /<%= table_name %>/1
  # DELETE /<%= table_name %>/1.xml
  def destroy
    @<%= file_name %> = <%= class_name %>.find(params[:id])
    @<%= file_name %>.destroy

    render :xml => {:notice => '<%= class_name %> was successfully deleted.'}
  end
end

Friday, September 24, 2010

Flex For Rails Scaffold

I’ve written a little component for connecting flex with rails scaffold as close as possible.

Step 1: Create a scaffold for Card

Within your rails application run the script:
./script/generate scaffold card id:integer timeStamp:timestamp data:text

(data types with Ruby and mySQL)


Step 2: Change the Card controller


Edit the Card Controller found at: myApp/app/controllers/cards_controller.rb and remove all view elements. this will make the controller omit pure XML structures


should result with the controller looking like:


class CardsController < ApplicationController
  # GET /cards
  # GET /cards.xml
  def index
    @cards = Card.all
    render :xml => @cards
  end

  # GET /cards/1
  # GET /cards/1.xml
  def show
    @card = Card.find(params[:id])
    render :xml => @card
  end


  # GET /cards/new
  # GET /cards/new.xml
  def new
    @card = Card.new
    render :xml => @card
  end


  # GET /cards/1/edit
  def edit
    @card = Card.find(params[:id])
    render :xml => @card
  end


  # POST /cards
  # POST /cards.xml
  def create
    @card = Card.new(params[:card])
    if @card.save
      render :xml => {:notice => 'Card was successfully updated.'}
    else
      render :xml => {:notice => @card.errors}
    end

  end


  # PUT /cards/1
  # PUT /cards/1.xml
  def update
    @card = Card.find(params[:id])

    if @card.update_attributes(params[:card])
      render :xml => {:notice => 'Card was successfully updated.'}
    else
      render :xml => {:notice => @card.errors}
    end

  end


  # DELETE /cards/1
  # DELETE /cards/1.xml
  def destroy
    @card = Card.find(params[:id])
    @card.destroy
    render :xml => {:notice => 'Card was successfully updated.'}

  end
end


Step 3: Client Side


To connect to the Rails server use an intermediate adapter called ActiveResourceClient.as

For testing, use the ServiceTester.mxml


good luck