Sencha Touch Resource Routing

{EAV_BLOG_VER:c29f605782f81784}

In MVC architecture, one of the great perks of routing is once you create the resourceful route, you usually don’t have to think about it again. Set up your actions and views, and you’re ready to go. Sencha Touch has brought the power of routing to their mobile JS framework, giving you an easy way to declare “URLs” which point to controllers and actions, but it does more than that, including abstracting History logic into the Dispatcher so that any Ext.redirect will automatically set the URL in the Ext.History space. You can read all you want about the Router and Dispatcher on Sencha’s site, but one thing I missed was the ability to declare a resourceful route. With Rails (3) you get to simply say “resources :transfers” and it will automagically recognize your index, create, and other routes for you. Thus, I added this handy little patch with 2 helpful methods (resources and alias), which allow me to do more than just “connect”, as so:

Ext.Router.draw(function(map) {
  map.connect('welcome', { controller: 'welcome', action: 'index' });
  map.connect('dashboard', { controller: 'dashboard', action: 'show' });
  map.connect('login', { controller: 'user_sessions', action: 'new' });
  map.connect('logout', { controller: 'user_sessions', action: 'destroy' });

  map.resources('transfers');
  map.resources('payments');
  map.resources('messages');
  map.resources('accounts');

  map.alias('bill_pay', 'payments');
  map.alias('message_center', 'messages');

  // more fluffy stuff...
});

Note the “map.resources” and “map.alias” lines, then check out the code below that does the work. Above, the map.resources(‘transfers’) line will produce 8 routes by default, including ‘transfers/index’, ‘transfers/new’, etc.

Get the Gist…

As you can see, the resources function simply generates the resourceful routes for you. The alias function is a convenience method really which, well, aliases a named route to another URL. So in this example, Ext.redirect(‘bill_pay’) is identical to Ext.redirect(‘payments’), both landing you in the index action of the payments controller. That’s it… feel free to use/comment at will. Happy coding! :)

Posted in Development, Sencha Touch | 3 Comments

Adding Callbacks to your Sencha Touch Controllers

Short and sweet. I needed a callback in several of my controllers to validate that a user is logged in, and if not redirect them back to the login screen. My file structure for this project looks a lot like Rails, so I have a config/initializers directory, and in that I’ve dumped a controllers.js file which contains the following:


Ext.Dispatcher.on('before-dispatch', function(interaction) {
  if(Ext.isFunction(interaction.controller.beforeFilter)) {
    return interaction.controller.beforeFilter.call();
  };
  return true;
});

Ext.Dispatcher.on('dispatch', function(interaction) {
  if(Ext.isFunction(interaction.controller.afterFilter)) {
    return interaction.controller.afterFilter.call();
  };
  return true;
});

In my application setup, I have a function (requireUser) that handles my logic for requiring that a user be logged in:


Ext.regApplication({
  // code, code, code...
  loggedIn: readCookie('user_credentials') || false,
  requireUser: function() {
    if(app.loggedIn) return true;
    app.flash.warning = 'Please login to continue.';
    Ext.redirect('login');
    return false;
  },
  flash: {
    notice: '',
    warning: ''
  }
});

Then in each of the files I want to require a user (or run some other before/after filter logic) I have something like so…


Ext.regController('accounts', {
  beforeFilter: app.requireUser,
  model: 'Account',
  index: function(options) {
    app.views.viewport.setActiveItem(
      app.views.accountsList, options.animation
    );
  },
  // other actions here...
});

For reference on Ext.Controller and Ext.Dispatcher, check out the Sencha Touch docs

Since it is Sencha on Rails, I feel like this approach adds a nice, seamless integration. Feel free to use, share, comment at will. Happy coding! :)

Posted in Development, Sencha Touch | 3 Comments

Mine’s Bigger Than Yours

First, let me preface by saying, I am not a “fangirl” of anything. I own 2 Macs, an AppleTV, an iPod, an iPad, and lots of other random techie gadgets that didn’t come from the brilliant minds in Cupertino. I do not, nor have I ever owned an iPhone, originally because I had *just* upgraded my phone with T-Mobile and signed a new 2 year contract when iPhone hit the market back in the summer of 2007. However, I have done iPhone development, and I have used at great length many iPhones so I am well aware of what they are capable of and why people buy them, so don’t discount my opinion just yet.

When the first-gen iPhone was released, it was flashy (although lacked Flash itself) and new; it opened the world’s eyes to the potential of mobile experience (I will punt on the use of the word “technology” here because, let’s be honest, the original iPhone did not match up to other smart phones on the market at the time). However, by supplying an open SDK for application development and presenting users with a slick, user-friendly interface, it rapidly became a fad… although I’m still uncertain as to the reason behind the massive amount of loyalty and defensiveness that goes along with owning an iPhone.

One theory I have for why the launch was so intense is this: For many years after Apple’s Mac line was completely revamped, there was always an elite status associated with Apple products, simply because at the time, Apple was only known for making computers – really expensive ones. Then came the iPod which cost significantly more than (roughly double) other MP3 players, but it looked better and if you had iTunes, you were able to very easily purchase and download music, then sync it to the device, essentially taking your Library with you wherever you go. Rhapsody eventually attempted this same business model, but the iPod precedent had been set. The story goes on to say that next was the iPhone, then the iPad but we’re aware of what’s gone down in the last 3 years so I’ll spare the details. So now we’ve seen a trend in the last decade… iPod, iPhone, iPad, each of them continue to blow the competition away in terms of market share. But, why? They’re sleek, sexy and they scream “status”. For the same reason that BMWs and Lexus’ are popular and longed-after, so are Apple’s iProducts. In the U.S., we’re known for living outside of our means, which means if a sparkly new toy costs less than $500, you *probably* have a credit card with at least that much available to spend. So if you could carry around a status symbol in your pocket in exchange for … well, nothing up front … why wouldn’t you? Right? At least that explains why Apple’s handheld devices have caught such wind, while their stationary counterparts are still no match for PCs.

I own Macs because I believe in the quality of the computer and doing graphic design and software development is so much faster, especially when you work with Linux, there’s minimal knowledge transfer needed when switching between environments. I own an AppleTV because dollar for dollar, it’s cheaper than cable considering I only watch about 3 TV shows and on rare occasion rent a movie. PLUS, I can use it to stream music from my iMac which alleviates the previous requirement of getting up and putting a different CD in the stereo. So I feel those purchases are justified. My iPod Nano was a birthday gift 2 years ago and I think I’ve used it a total of 7 times, and although it’s shiny and pink and in perfectly good condition, it’s essentially useless but I don’t think it’s heavy enough to be a paperweight. As for the iPad, didn’t buy that one either, was a hand-me-down from the CEO of my company who badly needed the 3G version and unloaded his completely antiquated, way uncool WiFi version down to me. I must say, I have taken quite a liking to the iPad, I even cuddle it to sleep at night playing WWF and Angry Birds – because I’m just *that* nerdy. Nonetheless, iPhone iLack.

Posted in Random, Technology | 1 Comment

Test your mailers in Rails 3

I don’t blog very often but I felt this was worth posting, since it left me scratching my head for a few minutes… Trying to test new mailers in Rails 3 (v 3.0.3 to be exact) with no real documentation – everything out there failed miserably since most examples show use of TMail. So here it is, my MailerTest:


require 'test_helper'

class MailerTest < ActionMailer::TestCase

  CHARSET = 'UTF-8'

  context "Forgetting a password" do
    setup do
      @user = User.create(valid_user_params)
      @expected = Mail.new
      @expected.content_type = 'text/plain'
      @expected.charset = CHARSET
      @expected.mime_version = '1.0'
    end

    should "send password reset instructions" do
      @expected.from    = "from@example.com"
      @expected.to      = @user.email
      @expected.subject = "Some Fancy Subject"

      assert_equal @expected, Mailer.password_reset_instructions(@user)
    end
  end
end

I’m using Shoulda with TestUnit, but in theory this should work with rspec, etc. Thanks to http://kpumuk.info/ruby-on-rails/testing-mailers-with-rspec/ for giving me a starting point… There’s definitely more you can add, like testing for the body content, but really this was all I needed for the purposes of this test.

Posted in Development, Rails 3 | Leave a comment

Who needs a codesitter?

Not this chick. Sorry Rails, I love you and all, but you have now taken a governmental stance by trying to regulate the output of my HTML and for that, I must say: “Quit it!!”. If you haven’t caught up yet, Rails 3 takes HTML escaping into its own hands and instead of requiring you to use h() to escape your output, it’s now automagically escaped for you. Yay, that’s great right? No. Wrong. Because it means now anywhere you *didn’t* want your code escaped, you’ll have to use raw() or #html_safe. Also wrong because it enables bad, bad storage techniques.

First things first, you should be sanitizing your code prior to storage. Worried about someone adding JS to your public blog and breaking the site? Easy solution, throw away the <script> tag before writing to the db. There are plenty of tools to help with this, xss_terminate being one of them, there are even built-in Rails sanitizers. If you do it right on the way in, you won’t have to worry about it on the way out. Ok, so let’s say you potentially miss something? It happens, no one is perfect. That’s the perfect case to use escape trickery ( i.e. h() ) in the areas where you might be worried about your output.

In general, if you develop applications that resemble ones I build in anyway, you have more HTML output that *doesn’t* need to be sanitized than does. Sorry to whichever genius thought it would be a great idea to escape everything, but you made a bad decision. It’s okay, have a beer, wallow in your sorrows and then give users the option to turn this off. In the mean time, it’s easy to disable it yourself.

In config/initializers create a file, call it whatever, I called mine output_buffer.rb and all you need is:

class Object
  def html_safe?
    true
  end
end

class String
  def html_safe?
    true
  end
end

Posted in Development, Ruby on Rails | Tagged , | 6 Comments