What did I get myself into???

Observations / Musings / Occasional Rants

Mobile Native App vs Responsive Web Site

Earlier today I was at a job interview where the interviewer asked me what my opinion was as far as whether the future of mobile development lay in native apps or responsive web sites. Not those exact words but you get the idea. Sadly, I not only did not really answer the question but the answer I did provide involved a totally unrelated topic. (You gotta love interviews.) Anyway, I decided to poke around a bit and see what I could learn on the topic not only so that I can be a more educated developer but also to avoid making an arse of myself if it were to come up again in any future interview.

So what did I learn??? Which is the “best” implementation to pursue? What solution will pour the most success upon you and your enterprise? — the Magic 8-Ball says, “It depends.” It’s far from a black or white, up or down, yes or no issue. What might be the best solution depends on the nature of your “app”, what you’re trying to accomplish, and what resources you have available (funds, time, expertise, patience).

If you’re building the next, great, super-interactive, processing-intensive mobile game or application, or you need your “app” to function offline, or you want to push data to your users, or you require significant interaction with the device’s core functions (SMS, GPS, camera, etc.) then it’s pretty much a no-brainer (at least for now) — your destiny lies in native-app land. Otherwise you have serious thinking and self-reflection to do. And by the way, don’t be surprised if “both” seems like the best answer. It may very well be. And if it is, maybe you want to start with a responsive site and work your way up from there. Just saying.

As far as which solution will shine brightest in the future, I think it’s safe to say that it’s too hard to tell at this point. Mobile, web, and wireless technologies are all changing so fast it’s difficult to predict what will be possible a year out never mind five or ten. My interview question would not have even made any sense ten years ago. “What’s a mobile app?” “A what web site?” It may not make any more sense ten years from now.

Below is a cool infographic from tablexi.com that provides a very basic guide for starting the process of deciding which route may be best for your needs.

Sharing Partials Across Models in Rails

So yesterday I was working on a Rails side project and I found myself in a situation where I had a partial that I wanted to use in several different views spanning several different models. My first impulse was just to place a copy of the partial in each of the models’ views folders but that felt very wrong. Not very “dry” at all. There had to be a better way. It took me about ten seconds of research to come upon a perfect solution. The kind of solution that as soon as you read about it you knock yourself on the forehead and go “Duuuuuuuuhhh!”.

The best thing to do is to create a “shared” subdirectory under app/views. Technically you can name the subdirectory whatever you want but “shared” seems so right. (DHH himself has also endorsed this approach.) And then you place all your shared partials in this new directory. Then in your code instead of render 'partial' you just have to render 'shared/partial'. That simple.

Modifying Rails ActiveModel Error Messages

Recently I was applying some validations to models on a Rails application I’m currently working on when I found myself in a bit of a double pickle. I had a need to get rid of an ActiveModel error message that was being generated and add one that wasn’t. How do you do either of those? Let me tell you how you can do both.

In Rails, when you try saving an object to a database or execute the .valid? method on it, if any model validations fail, error messages are written to an ActiveModel errors hash. This hash can be accessed by executing .errors.messages on the object. So let’s say you have a @user object you execute @user.save or @user.valid? on, after doing so, you can execute @user.errors.messages to check for any error messages. The resulting hash will look something like the following:

1
2
3
4
5
6
{:name=>["can't be blank"],
:email=>["can't be blank"],
:email_confirmation=>["can't be blank"],
:password=>["can't be blank"],
:password_confirmation=>["can't be blank"],
:password_digest=>["can't be blank"]}

This hash comes in handy to display the error messages to the user. Rails makes it even easier with the .full_messages method. For the errors hash above, @user.errors.full_messages results in

1
2
3
4
5
6
["Name can't be blank",
"Email can't be blank",
"Email confirmation can't be blank",
"Password can't be blank",
"Password confirmation can't be blank",
"Password digest can't be blank"]

Iterating through this array and printing the error messages is a snap. But …

What if you don’t want to print one or more of these error messages? For example, “Password digest can’t be blank”. That message will very well leave many a user scratching their head. Let’s get rid of it from the hash. @user.errors.delete(:password_digest) will do the trick. You can use .errors.delete(:key) to delete any of the messages in the errors hash.

1
2
3
4
5
["Name can't be blank",
"Email can't be blank",
"Email confirmation can't be blank",
"Password can't be blank",
"Password confirmation can't be blank"]

The error messages that are automatically generated result from failed validations on model attributes of the object in question. But what about validations you perform on any associations or any non-standard validations? If any of those validations fail and you want a message included in the ActiveModel errors hash, you have to add it in yourself.

In my situation, I performed a validation on a ‘roles’ association with my User model. Since the validation was not on an attribute of my User model, if the validation failed an error message would not be automatically generated and added to the errors hash. So after a little research I wound up using @user.errors[:base] << "error message". This added my message to the hash and made it available in the @user.errors.full_messages array. That easy.

And, should you want to, you can also add additional messages associated with specific model attributes in the same way. For example, if I performed some validation checking that the name entered is all lower-case, on failure I could execute @user.errors[:name] << "must be all lower-case". The resulting messages array winds up looking as follows:

1
2
3
4
5
6
7
["Name can't be blank",
"Name must be all lower case",
"Email can't be blank",
"Email confirmation can't be blank",
"Password can't be blank",
"Password confirmation can't be blank",
"Password digest can't be blank"]

Rails Console: Useful Tricks

The past couple of weeks I’ve been engaged in what could be best described as a love/hate relationship with the Rails console. I’m not alone. At times, it can be your best friend, other times it can leave you bewildered, frustrated, and wishing you had a bat. But it’s not always console’s fault, you have to know how to help console help you. There are a few tricks which can go a long way to helping you do that. Following are a few of the more useful and interesting ones.

Let’s start with a few oldies but goodies. reload! will reload your Rails environment in the console enabling any changes to your app’s models to be reflected. Much less annoying than exiting and then restarting the console every time you make a change. If what your seeing in the console output just doesn’t make any sense, it may not be a bad idea to execute reload! just in case your console environment needs updating. No guarantees but every so often it does the trick.

When you have a need to experiment but are worried about placing your database in great peril, have no fear, rails c --sandbox is there to alleviate your fears. Starting the console with the --sandbox option places your console environment in “sandbox” mode. Any database changes which occur while you’re in this mode will be rolled back when you exit. You can be as reckless as you want. Rails console has you covered.

In Rails console, the underscore, _, has never been more useful. In console, _ represents the output of the last command run. How often do you run a command with the intent of assigning the output to a variable but forget the variable assignment. That is situation where _ shines. You can assign the aforementioned variable with the command output by entering foo = _.

Now for one of my favorites. It’s very easy to remember, the letter y. If you place a y ahead of your command (y User.first), the output will load to YAML. The resulting formatting makes the output immensely easier to read. This works with most model objects and data structures. y is worth it’s virtual weight in gold when dealing with nested hashes.

helper can be used to access Rails helper methods in the console. For example, helper.pluralize(3, 'dog') results in "3 dogs". helper.number_to_currency(25.32) results in "$25.32". helper.link_to 'Sign out', '/sign_out' results in "<a href=\"/sign_out\">Sign out</a>".

The app object can be used to access your controllers through the console. For example, app.new_user_path returns "/users/new". app.cookies returns a Rails CookieJar object with which you can access session cookie data.

And last but not least, I can highly recommend Ryan Bates’ Railscast “Console Tricks”.

When application.html.erb Just Doesn’t Cut It

Recently I was working on a Rails application on which I had a need to apply layouts to views other than the default application.html.erb alyout. The following is what I discovered on how to do that. (I make no claim that the following are the only and/or best ways to do this. Rails being Rails there are probably at least ten additionals ways.)

Controller Level Layout

If you wish to use a different layout for all the views associated with a particular controller, you have two options. The first option is to create a new layout with the same name as the controller you wish to apply it to. For example, let’s say you have a controller named UsersController in your app, you could place a layout file named users.html.erb in the app/views/layouts folder. Rails will then apply the users.html.erb layout to all the Users views.

The second option is to include layout "alternate_layout" in the controller’s class defnition. The alternate layout file must be present in the app/views/layouts folder. In this case the file’s name does not have to be the same as the controller’s.

1
2
3
4
5
6
7
class UsersController < ApplicationController

layout "alternate_layout"

### controller code ###

end

Action/View Specific Layouts

But what if you don’t want to apply an alternative layout to an entire controller? What if you only want to apply it to specific views? You have a few options here also.

One option is to specify which controller actions an alternative layout is to be apllied to. You can do so like this:

1
2
3
4
5
6
7
class UsersController < ApplicationController

layout "alternate_layout", only: [:index, :show]

### controller code ###

end

application.html.erb will be applied to the remainder of the action views.

A second option is to add a method in your controller which determines which layout to use at run time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class UsersController < ApplicationController

  layout :resolve_layout

  ### controller code ###

  private
  def :resolve_layout
    case action_name
      when 'show'
        'show_layout'
      when 'index'
        'index_layout'
      else
        'application'
      end
  end
end

And if you choose you can specify an alternative layout at the controller action level.

1
2
3
4
5
6
7
def show

  render :layout => 'show_layout'

  ### action code ###

end

Don’t Miss Out: NYC Ruby/Rails Community

So I just finished my third week of the Flatiron School and the experience has been nothing short of fantastic. Hard work, but all worth it. And one of the bonuses of being a student at the school is having guest developer notables come in and share their knowledge, insights, experiences, and excitement about what they do with us.

I thought I would write about what has been a common thread amongst several of their talks, praise for the NYC Ruby/Rails community. I couldn’t agree with them more. My experience with the community began over a year ago with the first Meetup I ever attended. It was a Thursday Hacker Hours hosted by Aidan Feldman (a recent speaker at Flatiron). Aidan was the first person I met/spoke to at a Meetup. The second person I spoke to, introduced to by Aidan, was Blake Johnson (a current teaching assistant at Flatiron). After that meetup there have been many others.

Don’t be mistaken, it’s not all about meetups, there are also hackathons, code retreats, happy hours, and conferences where the community congregates to share ideas, stories, knowledge, lessons learned, and sometimes just generally hang out and have a good time with like-minded people. (The occasional free food and beer doesn’t hurt either.) And you never know who you might meet or what you may learn at one of these events. But one thing you can be sure of is that if you need help with something or want to learn more about anything, all you need to do is ask. Don’t be shy. Members of the NYC Ruby/Rails community are always very willing to help and they are extremely welcoming and accepting of those who may just be getting started. It doesn’t matter if you are an aspiring developer or maybe want to turn your “next big thing” idea into a reality.

I have never left a meetup or other community event without having learned something new. Whether it’s about some new Ruby gems, or Rails projects, or development techniques/tools, or lessons learned, or many other things, there is always an opportunity to learn. Sometimes you learn a whole lot! The community can be an invaluable resource for someone who is trying to learn on their own as I was. And all that from experienced programmers who have seen and done it all. Many of whom where at the same point you are at earlier in their careers so they can identify. It’s ok to admit that you’re just a beginner. No one is going to make fun of you. And the more questions you ask the more you will learn. Take advantage.

Can One Ever Know Too Many Command Line Tricks?

I don’t think so either.

Looking through some presentation decks on speakerdeck.com, I came across two presentations addressing this which I can never can get enough of. The two decks are ”Unix Command Line Productivity Tips” by Keith Bennet and ”Time-saving tricks on the command line” by Janos Gyerik.

Following are some of the command line gems I gathered from their presentations. If you are unfamiliar with any of them, I strongly encourage you to try them out. I suspect you will like what you find.

  • cd -

(The dash is part of the command) Ever find yourself jumping back and forth between two directories? This puppy toggles the current and previous directory.

  • pushd and popd

Pushd is short for ‘push directory’ and popd for ‘pop directory’. If you execute ‘pushd .’ and then move to a different directory, you can then execute ‘popd’ and it will take you back to the directory you pushed previously. How cool is that?!?

  • !$

Not pretty but this captures the last parameter in the previously executed commad. For example, if you ‘touch file.txt’ and then ‘subl !$’, Sublime Text opens file.txt.

For your editing on the commad line pleasure:

  • ctrl - w

Deletes the last word you have entered on the commad line

  • ctrl - k

Deletes from the cursor position to the end of the line

  • ctrl - y

Pastes whatever you deleted in the previous commad

  • cntrl-a

Jump to the start of the line

  • cntrl - e

Jump to the end of the line.

  • option - left/right

Skip left/right one word at a time

Enjoy.

No Turning Back Now

Today I gave notice at my school that May 31st would be my lasy day there. The following Monday I start the Flatiron School. It was rather nerve wracking. The mental drafts of what to say and how to say it changed every five seconds heading into the appointed time. In the end, I can’t even remember exactly what I said. However, I was grateful that the response was very positive. All the administrators I spoke to were very understanding and wished me well. Not that I was really expecting any sort of negative reaction, but the human mind seems to always tasks at least a few neurons to formulating and screening such scenarios.

We must be willing to get rid of the life we’ve planned, so as to have the life that is waiting for us.” - Joseph Campbell

Moving Along

So the Flatiron pre-work moves along. I’ve gone through the command line lessons and have moved on to SQL and databases. I worked with SQL some back when I was with Accenture so I hope any residual familiarity that remains kicks in. Really want to get to the HTML and CSS material. Those are areas in which my lack of knowledge greatly frustrates me. Soon enough.

Visited the school tonight to attend one of the sort-of weekly Flatiron Presents meetups. There was a bonus presentation by Lucas Mazza of Plataformatec in Brazil. It felt good to tell some current students who knew I had applied that I had been selected for the next session. Some even invited me to drop by on Saturdays if I wanted any help with the pre-work. They said some of them are always around. I believe it. It was very nice of them to offer.

A jug fills drop by drop.” - Buddha

The Beginning of the Beginning

Finally! The weather is turning for the better. After leaving work today, I actually sat in my hot car in the parking lot for a full minute enjoying the hotness. In a month I’ll be complaining and reaching for the AC knob but not today. I just wanted to soak it in for a bit. It’s been a while.

I started working on the Flatiron School pre-work today. It begins with some website “basics” which are pretty much just that. I watched several Team Treehouse videos on website basics and aesthetic foundations. Felt like I was in art class for a bit. Lines, shapes, hue, contrast, symmetry, balance, … Good stuff coming though.

Ended the evening on an extremely pleasant note. Met the girlfriend in the city at NYU where she works, we strolled to McDougal Street to grab some delicious kati rolls to go, and then we headed to Washington Square Park. It was so enjoyable and relaxing sitting there soaking in the beautiful weather and the laid back buzz in the park. Many people walking around, sitting around enjoying what we’ve all been missing for so long.

The grand essentials of happiness are: something to do, something to love, and something to hope for.” - Allan K. Chalmers