Showing posts with label rails. Show all posts
Showing posts with label rails. Show all posts

Tuesday, 10 December 2013

Ember.js and Rails - pt 2/x


Ok, it's been a couple of weeks (this is not the only thing I'm working on) and not too much progress. Getting my head around Ember has been a nightmare, not helped at all by the fact it is a moving target, especially in the case of Ember-Data.
So much of a moving target that the whole thing shifted into RC mode.
So, a lot of changes have had to be made.

Die, Coffeescript, Die Die Die.


The other thing is I cannot express deeply enough my hatred of Coffeescript. It seems, well, pointless. It seems to be used to write Javascript and I really don't see any advantages over just writing Javascript. It is argued that it is smaller, but that is not really the point when it is unreadable.
It is like I say that I write my letters in Japanese, which will eventually be converted to English, because in Japanese I can use a single Kanji character to express a whole word or concept in English. The fact that you have to learn Japanese to accomplish something you could adequately do from the start is the killer.

So, I have ditched Coffeescript for now.

Ember Store

So, the store.js file now looks like this:

HorseFeeder.ApplicationAdapter = DS.RESTAdapter.extend({
    namespace: 'api/v1'
});

Lesson #1 - don't use DS.ActiveModelSerializer

If I put this line in:

HorseFeeder.ApplicationSerializer = DS.ActiveModelSerializer.extend({});

everything stops parsing. Even though I am using ActiveModelSerializer on the Rails side.

Routes

Routing has changed in Ember-Data. It's a little simpler, but, they got rid of the store object, which means that you can't call the store directly from Firebug.

Routes now look like this:


HorseFeeder.EventDaysIndexRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('event_day');
  }
});

HorseFeeder.EventDaysShowRoute = Ember.Route.extend({
  model: function(params) {
    obj = this.store.find('event_day', params.event_day_id);
 return obj;
  }
});

Serializers

Right now it looks like this (see 'current crisis points' below):

class EventDayIndexSerializer < ActiveModel::Serializer
  attributes :id, :day
  has_many :events, embed: :ids, key: :events
end 

Note that if I don't do that key:  :events thing Ember doesn't see the objects.

Current Crisis Points

Right now the backend is spewing out data and the front end is taking it. i.e. I am doing what all the Ember tutorials on the web do. But that is not the real world. Here are a list of my current pain points

  1. When I send out a list of objects in an index call, I do not want to send out all their associations/children because that would mean basically dumping the whole database, right?! As all objects are related to each other in my model it is unmanageable and slow. I am fixing this right now by writing serializers that only dump out the object, not the children.
  2. If you do what I do above (with the limited data at the index level) I cannot figure out how to get Ember to reload the object on the 'show' so I can fill in all the data. To me this seems to be such an obvious way to do it I can't believe I've spent 2 days trying to get it to work.
  3. What doesn't the ActiveModelSerializer in Ember work for AMS in Rails?
  4. The pain and time so far have caused me to question the wisdom of using Ember!
I have a few open StackOverflow questions... so hopefully my next instalment will be all sweetness and light.

Learning Ember.js and Rails Part 1 (of many!)

I’m starting on a new, massive, application. I don’t like to make things easy on myself so instead of doing this in my usual RoR/jQuery stack I am jumping in and doing this with:
  • Ruby 2
  • Rails 4
  • Ember.js
This presents some challenges, not the least of which is Ember.js. I’ve never used a front end framework before. But I can see the power of it, plus, one of the key features of this new app is that it will provide a data api. With Ember.js, I believe, almost all interaction with the data will be through an api, so it seems like a good start and a way to sanity check what is coming in and out to other consumers of this api.

I know I suck at writing blog posts, but, I will try and document this journey because I have looked around and there doesn’t appear to be too many resources for people doing this. Everything I have found is much too simple and is not for the experienced Rails developer.

I did find one good resource from Tony Coconate (http://www.devmynd.com/blog/2013-3-rails-ember-js) and I am starting off from that. Now, that may or may not be a good idea!

Setup

I set up a new rails app. Then chucked some stuff into the Gemfile:
# front end
gem 'ember-rails'
gem 'ember-source'
gem 'ember-auth-rails'
gem 'ember-auth-source'

Create Resources

After, my first steps were to all but ignore the front end. 

I created my models as resources, like in Tony’s article. For example:

rails g resource Trainer name:string additional_info:text provider:references provider_key:string —no_helper

This means you end up with:
  • a controller, 
  • a model
  • a serializer - from active model serializer
  • a db migrate script 
  • two coffee script views (trainer and trainers)
  • entries in routes.rb
Moving Controllers

Again, as per Tony’s article, I am going to use Ember Data (whether or not it is ready for prime time now is not too important. This app won’t see the light of day for months yet). So, I move all the controllers from /app/controllers to /app/controllers/api/v1 and put Api::V1:: at the front. I also put in standard actions. So now my controller looks like this:

class Api::V1::TrainersController < ApplicationController
    respond_to :json

    def index
        respond_with Trainer.all
    end

    def show
        respond_with Trainer.find(params[:id])
    end
end

Modify Routes

I also modify routes.rb to look like this:

namespace :api do
    namespace :v1 do
        resources :trainers
    end
end

At this point I can point my browser at localhost:3000/api/v1/trainers.json and get a list (assuming I have data!) or to localhost:3000/api/v1/trainers/1.json to get the single record.

So far so good.

In my mind the data side of the app is on the way. I will not worry about any more Rails stuff for now.

Next is learning Ember.js 

Wednesday, 25 September 2013

HTTP Basic authentication with Rails for iOS

Recently I've been getting into iOS and developing a interesting iOS app (more info coming soon!)

But, as the app is all about showing data of course I needed to create an API in my rails app to feed that data. But, I didn't want someone else to be able to grab it.

The Rails App Side

Configure a custom MIME type

First thing I did was set up a custom mime type in initializers/mime_types.rb:
Mime::Type.register_alias "text/json", :theapp
That let me call urls like /give_me_data.theapp

Add the 'respond_to'

In the applicable controllers add a respond_to (well, I already had one, so add to it):
respond_to :html, :xml, :theapp

Make templates with json_builder

I luuuvvvvv the json_builder gem. So I created a whack of templates with the .json_builder extension. Because of the mime type setting it would automatically get called.

Add the http_authentication stuff

I am a little bit lazy, so, I just chuck this into my application_controller. That means that all :theapp requests need authentication:

protected
def http_basic_authentication
    if request.format == :ios
        authenticate_or_request_with_http_basic do |username, password|
            username == 'myAmazingApp' && password == 'theBestestPasswordEver'
        end
    end
end

The iOS app side

The URLs

Simply chuck your authentication stuff into your urls:
NSString *const RegionDataBaseURL = @"http://myAmazingApp:theBestestPasswordEver@localhost:3000/regions/%@.theapp";

Pulling...Data

I do my stuff like this (thanks to Ray Wenderlich):
  dispatch_async(kBgQueue, ^{
    NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:RegionDataBaseURL, [self.region permalink]]];
    
    NSData* data = [NSData dataWithContentsOfURL: url];
    [self performSelectorOnMainThread:@selector(fetchedRegionData:)
                           withObject:data waitUntilDone:YES];
  });
Yes, I could also put the username and password in some other place and sub it into the URL, but brute force works for now.

Like I say, I am starting out in iOS so maybe this is too noddy for all you pros, but, it works.

Tuesday, 24 September 2013

The gotcha's in Node.js - or how I reduced our bandwidth by 75%

So, I have this great application that distributes, in pretty close to real time, information across hundreds of screens in Germany. It does this with a combination of Rails, Node.js and HTML/Javascript.
But we noticed MASSIVE traffic.
My model was to pump out the data and have intelligent pages decide what to show.
It turns out this is very inefficient.

Not ready for primetime

We have 4 'channels' of information. The software had originally been built on a 'tv station' idea. And, in TV, everything gets pumped down the line (or over the air) and then the tv 'tunes in' to a channel and shows the appropriate content.
In our case, we had a 'screen structure' message that was sent out once a minute and then in between each element on the screen would send out its own updates if it was altered.
It was the screen structure message that was the problem.

The old way

I was doing something like this on the page:

client.subscribe('/source', function(message) {
    window.setTimeout(function() {
        process_source_message(message);
    }, 1);
})

And in Node app.js I was doing this:
app.post('/source_state', function(req, res) {
    bayeux.getClient().publish('/source', req.body);
    res.send(200);
});

And in Rails, something like this:
RestClient.post [NODE_CONFIG[Rails.env]['node_url'], NODE_CONFIG[Rails.env]['source_update_path']].join('/'), JSON(json)

So, every page would get every 'source' message.

The new way

I realised that I should have the pages listen to their specific channel. I had got hung up in the past on the idea that I didn't know the name of the source in advance - it could be anything as it is user defined.

But, inside of the source JSON was already this:
json = {
    "source" => {"name" => source.slug}
}

It turns out I didn't need to change the back end (Rails) at all.

In the app.js I just needed
app.post('/source_state', function(req, res) {
    bayeux.getClient().publish('/'+req.body.source.name, req.body);
    res.send(200);
});



Sunday, 30 October 2011

installing sunport_rails on ubuntu production

We've added search functionality to Toygaroo with Solr via sunspot_rails.

If you are going to install it on Ubuntu then make sure you do:

sudo apt-get install openjdk-6-jdk

First!

Monday, 26 September 2011

Expiring fragments from daemons

We have an application that gets its data from a series of daemons that go out and read in data. This works great, except, we are caching pages. And I'd like to expire those pages based on an update.
It turns out that an Observer doesn't have access to expire_action or fragment. And a Sweeper is not called from data-only (i.e non-controller) updates! Buggers!

But there is a solution. You can call the sweeper directly from your importer:

MySweeper.instance.clean_up(model_instance)

This works, except I couldn't get it reliably to expire the actions. So, I used direct calls to Rails.cache.delete to do this.

Thinking about it, I guess I could then have just written an observer! As those do get called from controller-less updates.

Monday, 18 October 2010

Customizing Devise to a pseudo multi-stage Signup

The Requirements!
On our new site we want to have a kind of multi-stage signup. The first page the user chooses a type of subscription, the second page they create their account, with address information, and the third page they enter their billing info. If they don't do the third stage that's ok as we will warn them that their account is incomplete (and they won't get any services until they give us the billing info)

We are doing this new site in Rails3 and I thought I'd use Devise as the authentication engine. In our old site we use Restful Authentication, which has been awesome. But Devise seems to be the thing all the kids are into today!

So here's how we did it:

Step 1:
Create a New Controller
We created a new controller to handle the first stage of the signup. It's very simple. It only is a "new" method (for now) as we do no saving or updating of the subscription.

rails g controller subscriptions new

create app/controllers/subscriptions_controller.rb
route get "subscriptions/new"
invoke erb
create app/views/subscriptions
create app/views/subscriptions/new.html.erb
invoke rspec
create spec/controllers/subscriptions_controller_spec.rb
create spec/views/subscriptions
create spec/views/subscriptions/new.html.erb_spec.rb
invoke helper
create app/helpers/subscriptions_helper.rb
invoke rspec
create spec/helpers/subscriptions_helper_spec.rb



The controller looks like this:
class SubscriptionsController < Devise::RegistrationsController
def new
@subscription_plans = SubscriptionPlan.visible
end
end


Pretty basic stuff!

The view is:
<% title "Sign up" %>

<div>Pick a subscription</div>
<% semantic_form_for :subscription, :url => users_sign_up2_path, :html => { :method => :get } do |form| %>
<%= form.input :plan_id, :as => :radio, :collection => @subscription_plans.map{|sp| ["#{sp.description}", sp.id]} %>
<% form.buttons do %>
<%= form.commit_button "Continue" %>
<% end %>
<% end %>


Step 2:
Routes!
We needed to add some custom routes to the users block to let Devise know what was going on:
  devise_for :users do
get "/users/sign_up" => "subscriptions#new"
get "/users/sign_up2" => "registrations#new"
end


The first line says use the subscriptions controller as the first stage of the sign up. That way we don't need to change any helpers and can do things in the standard Devise way. The second adds the second stage - the actual user new-ing and creation:

Step 3:
Override the Registrations Controller.
This is where 'the good stuff' happens! Note that we don't need to override the create method. Devise has a hook in it for building the model, so we override that instead.
It should be noted that this only works if the model can't be saved - i.e. your validations are complete. In our case we are creating 3 models in 1: subscription, address and user. The subscription and address will get saved if the user gets saved. So, we have validations in the user requiring a subscription and address. Then validations on the address to make sure it is good. That way if the validation of the address fails the validation of the user fails and we get chucked back out the the new user form.
The code might say it better!

class RegistrationsController < Devise::RegistrationsController
def new
@address = Address.new
begin
@subscription_plan = SubscriptionPlan.find(params[:subscription][:plan_id])
rescue Exception => e
redirect_to users_sign_up_path and return
end
@user = User.new
end

protected

# Build a devise resource passing in the session. Useful to move
# temporary session data to the newly created user.
def build_resource(hash=nil)
address_info = params[:user].delete(:address) rescue {}
begin
sub_info = params[:user].delete(:subscription_plan)
@subscription_plan = SubscriptionPlan.find sub_info["id"]
rescue Exception => e
redirect_to users_sign_up_path and return
end

subscription = Subscription.new(:subscription_plan_id => @subscription_plan.id)

@address = Address.new(address_info.merge(:country => "US"))

@user = User.new(params[:user].merge(:first_name => @address.first_name, :last_name => @address.last_name))
@user.subscription = subscription
@user.current_shipping_address = @address
end

def after_sign_up_path_for(resource)
new_user_billing_detail_path(resource)
end

end


Also note that we override 'after_sign_up_path_for'. That way we move the user onto the third stage of the process - the billing info - if they sign up.

This is still in early stages, and not yet live, but the process seems to work.

Sunday, 20 December 2009

SSL_Requirement

I use the ssl_requirement plugin to let me specify what actions need to be secure.

But - I found it limiting. I needed to:

  1. Specify what the secure domain was - we only have a certificate on the base domain, not all the subdomains

  2. Be able to easily turn it off in different environments


So, I forked a version off that does that. If you have the same needs (and, like me, prefer a plugin over a gem) check mine out!

Saturday, 19 December 2009

Apache + Passenger + SSL + OSX

Recently I wanted to do some work on parameter passing and also how to keep parameters passed to SSL pages through redirects.
The first stumbling block was to get passenger and apache to play nice with SSL on OSX

I am running Leopard (not SNOW Leopard) and here is what I did to get it to work. I couldn't find anything specific on the net about this, so I thought I'd chuck this up here. There may be nicer, better ways of doing this.

1 - Create the cert


Apple has a page on creating a cert. This all worked fine except the locations aren't right. This page must be for Tiger.
For Leopard apache is in /etc/apache2 (or /private/etc/apache2 depending on your installation).
It all seemed to work fine for me as written apart from that.
You end up with a ssl.key directory in your apache2 directory. You may wish to rename this domain.ssl.key if you are doing multi domain development. I am, but this is the only domain I wanted to check ssl on.

2 - Apache and SSL


This turned out to be easier than expected, but everything's easy when you know how!
Edit /etc/apache2/httpd.conf
All I needed to do is put this line around line 40:
Listen 80
Listen 443


You add the Listen 443

3 - Passenger files


I did this by hand. As far as I know you can't do this via the prefpane,
I have used the PrefPane to create the vhosts file.
sudo vi passenger_pane_vhosts/mydomain.local.vhost.conf

Then add:

<VirtualHost *:443>
ServerName mydomain.local
ServerAlias mydomain.local es.mydomain.local en.mydomain.local
DocumentRoot "/Users/smyp/development/mydomain/public"
RailsEnv development
<directory "/Users/smyp/development/mydomain/public">
Order allow,deny
Allow from all
</directory>

# SSL Configuration
SSLEngine on
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP
SSLOptions +FakeBasicAuth +ExportCertData +StdEnvVars +StrictRequire

#Self Signed certificates
SSLCertificateFile /private/etc/apache2/ssl.key/server.crt
SSLCertificateKeyFile /private/etc/apache2/ssl.key/server.key
SSLCertificateChainFile /private/etc/apache2/ssl.key/ca.crt

SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0

</VirtualHost>


Basically what you do is copy all the stuff from the area and then add in the extra SSL config.
Just point the crt, key and ca.crt files to the ones you created in step 1 from the apple doc.

That's it! You should be ready to go!

Let me know if there are any errors in this and I'll correct them... I wasn't making notes as I went along, so this is done from looking back, so maybe I've left something out.

Wednesday, 16 December 2009

redirect_to : pass all parameters

On filmamora we redirect people to the language version we think they want. This is done with a subdomain for the language.
As if that wasn't painful enough, it now seems I was stripping out additional parameters - like the parameters passed in from our mailings that triggered Google Analytics campaigns.
Doh!

So this:
  def language_redirect
redirect_to :subdomain => session[:language] unless RAILS_ENV == 'staging'
end


Needed to become this:
  def language_redirect
p2 = params.merge({:subdomain => session[:language]})
redirect_to p2 unless RAILS_ENV == 'staging'
end


Such a small change - such a big difference! Marketing types appeased!

Friday, 24 July 2009

move from ec2onrails

Recently the performance on FilmAmora.com has been plummeting. And I had no idea why. Often apache was timing out waiting for a mongrel. Very little development has happened recently on FilmAmora, so I was stumped.
So - like a good developer - I took this as a chance to make a drastic move from ec2onrails machines to straight ubuntu, with everything else installed by hand.

It has made a HUGE difference. So much so that I could actually drop a machine from the configuration and still have better response times.

I followed these instructions to get started: rails-nginx-passenger-ubuntu. I also switched to nginx and ruby enterprise edition - just to make following the instructions easier.

So far so good. It took a couple hours and presto a leaner meaner installation. My NewRelic Apdex score went from .5 to .9.

Friday, 17 July 2009

expiring action_cache

I was having a bugger of a time expiring my cache. The problem was the cache_path.
I have index actions that take filters. So, I created a cache_path for my action caching:

caches_action :index, :layout => false, :cache_path => Proc.new { |c| "#{c.params[:league_id]}/index/#{c.params.values.sort.to_s}" }


Which means that all my caches end up in a nice tree of 'views/[league name]'. But, how to expire a whole part of the cache tree when there could be dozens of nodes as people could be searching on last names too.

What I found was that expire_action was NOT the way to go. expire_fragment lets you pass in a regular expression. Now in my sweeper I have this:

  def expire_cache_for(player)
expire_fragment(%r{views/#{player.league.to_param}.*})
end


Which will expire all the cached code for the player's league.

Saturday, 6 June 2009

i18n

We've (finally!) moved FilmAmora up to rails 2.2.2 - and not without some headaches.
The biggest ones seem to revolve around translations. We were using po/mo files and that worked great. Moving to 222 required some changing of gems (to fastgettext) and other things. But we were left without standard translations of all the ruby messages for some reason.

The guys at rails i18n.org came to the rescue!

Their Github project

Has config files for most locales that will cover all the standard messages. A real life saver!

Sunday, 24 May 2009

Forcing a different render format

I am writing an OAuth system for FilmAmora for the iphone app (and anything else I guess) to use.
I want to always output xml from the controller that is handling the catalog output... but how to do that!

I came up with this:

  def list
render :template => "/catalogs/list.xml.builder", :content_type => "text/xml"
end


This will always output xml (with the right mime type) no matter what the requested format was.

Monday, 18 May 2009

Creating a new rails app with an old version

After much hunting I found how to do this

gem list rails

to see what versions you have. I need to create a 2.1.2 rails app. you can do that by issueing this command:

rails _2.1.2_ my_app

Sunday, 10 May 2009

cookies and hosts / domains

I have been struggling for weeks with a problem of users being logged in to mysite.com, but not en.mysite.com and es.mysite.com. I posted on Ruby Groups and even tried to hire someone to do the work... but to no avail.
Finally I think I cracked it today.

Two things. First, for some reason doing this didn't work:
  if RAILS_ENV == 'production'
config.action_controller.session = {
:session_key => '_my_session',
:session_domain => '.mysite.com',
:secret => 'xxx'
}
else
config.action_controller.session = {
:session_key => '_my_session',
:session_domain => '.mysite.local',
:secret => 'xxy'
}
end


So, I substituted this into each environment file:
config.after_initialize do
ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS[:session_domain] = '.mysite.local'
end


That got my session's having the correct domain set (.mysite.com) meaning that the session was saved across subdomains.

Cookies

But then I encountered a second problem. Cookies.
After switching to hide and seek / show and tell methods to enable me to page cache even pages that had logged in status all over them (more on this in another post) I needed some user info in a cookie. But my cookies were tied to the subdomain!
I was setting the cookies like this:

      cookies[:current_user] = {
:cart_items_count => cart_items_count,
:nothing => 1
}.to_json


I thought, ok I just need to add the domain in:
      cookies[:current_user] = {
:cart_items_count => cart_items_count,
:nothing => 1,
:domain => ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS[:session_domain]
}.to_json


No...this didn't work. Everything was being chucked into the cookies 'value' and not the domain field (same happened if I added in an expires_at key). What was going on?
Aha! It is the json-izing.

So, I moved that out to a seperate variable:
      value = {:cart_items_count => cart_items_count, :nothing => 1}.to_json
cookies.delete :login, :domain => ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS[:session_domain]
cookies[:current_user] = {
:value => value,
:domain => ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS[:session_domain]
}


Now my cookies had the proper domain info and the value was still proper json. And now my users are logged in across sub domains!

Saturday, 21 March 2009

backgroundrb by hostname

I love backgroundrb - the way to run scheduled tasks and async workers. BUT on my setup I wanted to run certain backgroundrb tasks on one machine and certain ones on another (for memory reasons and also for testing).

I couldn't find something that did that so I forked backgroundrb into my own repository on GitHub. You can find it here.

You can now have a config file like this:
# A Sample YAML configuration file
---
:backgroundrb:
:ip: 0.0.0.0 #ip on which backgroundrb server is running
:port: 11006 #port on which backgroundrb server is running
:environment: production # rails environment loaded, defaults to development
:debug_log: true # whether to print debug logs to a seperate worker, defaults to true
:log: foreground # will print log messages to STDOUT, defaults to seperate log worker
# :result_storage: memcache # store results in a mecache cluster, you also need to specify location of your memcache clusters in next section
:persistent_disabled: true # turn this off if your application doesn't use backgroundrb's persistent/enqueued tasks system
:persistent_delay: 10 # the time (seconds) between each time backgroundrb checks the database for enqueued tasks
:per_environment: true

# You specify your worker schedules here
:whatever.local:
:backgroundrb:
:environment: test
:schedules:
:test_worker: # worker name
:test: #worker method
:trigger_args: */5 * * * * * * #worker schedule
:data: whatever

:phils-mac-pro.local:
:backgroundrb:
:environment: development
:schedules:
:test_worker: # worker name
:test: #worker method
:trigger_args: */5 * * * * * * #worker schedule
:data: phil


You can launch backgroundrb with a specific hostname like this:

./script/backgroundrb --hostname=whatever.local


I've created Capistrano tasks that fire up an instance on 2 servers and now they act differently based on hostname.

Sweet!

Friday, 13 March 2009

Generating sitemaps and xml catalogues

One of the things we have to do at FilmAmora is generate a catalogue of our films. This is used in a few ways, but principally to drive our recommendations system.

I stumbled across this great blog entry:
Generating-Sitemaps-With-Rails that not only tells you a very nice way of generating sitemaps but also gave us great ideas for using the same technique to generate our catalogues.

Awesome!

Wednesday, 11 February 2009

DropDown menu for Blueprint tabbed menus

I love blueprint css! And I also love the tabs menu plugin for it. But, we neede drop down menus on FilmAmora. So I wrote a little extension that gives you that. It's not perfect, but, it works for now.

Find it here:
Blueprint_dd