Posting to a Facebook Page using Ruby on Rails

You have always been able to post to Twitter through Atomic Leagues but until recently I hadn’t added posting to Facebook as it is a little more complicated.  With Twitter you authenticate to the user account and that’s it.  With Facebook, because most teams, leagues, and organizations have a dedicated Facebook page I needed to post to the page and not the actual user account.  It turned out to be easier than I thought it would be.

Gems:

  1. The omniauth gem with the omniauth-facebook strategy gem.
  2. The koala gem for gaining access to a user’s Facebook pages.

Code:

Make sure in the configuration for omniauth-facebook that you have publish_stream and manage_pages in your scope

omniauth.rb:

 Rails |  copy code |? 
1
2
  provider :facebook, FACEBOOK_KEY, FACEBOOK_SECRET, :scope => "publish_stream, manage_pages"
3

Create the Social Media model:

 Rails |  copy code |? 
1
2
  rails g model SocialMedia uid:string, token:string, page:string
3

On the return of the Facebook authentication using omniauth, I capture the token returned from Facebook.

 Rails |  copy code |? 
01
02
@social_media = SocialMedia.new
03
auth = request.env["omniauth.auth"]
04
 
05
@social_media.uid= auth["uid"]
06
@social_media.token = auth["credentials"]["token"]
07
 
08
@social_media.save
09
 
10
redirect_to edit_social_media_path(social_media) and return
11

At this point you can list of pages for the authenticated Facebook user using Koala:

 Rails |  copy code |? 
1
2
@social_media = SocialMedia.find(params[:id])
3
user_graph = Koala::Facebook::API.new(@social_media.token)
4
@pages = user_graph.get_connections('me', 'accounts')
5

The user can then pick which of the pages they would like to post to:

 Rails |  copy code |? 
1
2
<%= f.select :page, @pages.map {|u| [u['name'], u['id']]}, :include_blank => true %>
3

If they select the blank entry it means they want to post directly to their Facebook account instead of a Facebook page:

 Rails |  copy code |? 
01
02
@social_media = SocialMedia.find(params[:id])
03
@social_media.attributes = params[:social_media]
04
user_graph = Koala::Facebook::API.new(@social_media.token)
05
 
06
#If the secret key is blank then post to the user account.
07
if (@social_media.secret.blank?) then
08
  user_graph.put_wall_post("posting to user account") #Post to the user account, requires publish_stream permission.
09
else
10
  #Get the information for the page.
11
  page_graph = Koala::Facebook::API.new(user_graph.get_page_access_token(@social_media.secret))
12
 
13
  page_graph.put_wall_post("posting to page") #Post to the page, requires publish_stream permission.
14
end
15

That is about it, I may have left out a few details so if anyone tries to walk through these steps and has issues, please let me know.

Book Review of Small Giants

I had high hopes for Small Giants by Bo Burlington but I guess I wasn’t quite as impressed as I thought I would be.  It was interesting but I thought there was a lot of repetition in the book and overall I didn’t think the author made a convincing enough argument as to what makes these companies great.

The other issue I had was that the book was written in 2003, which I didn’t realize until I started reading it.  I was a bit more skeptical about everything I read after that and was curious if any follow-up had been done on where the companies are today.  Apparently much more than that has taken place.

I was surprised to find while searching that a whole movement kind of sprung up around this philosophy of “defining success by more than just the bottom line.”  Reading over the Small Giants website and the values it espouses, I got a sense for more of what the book was about and thought it did a very nice job of summarizing the six core values from the book.

The main takeaways I got were this: first, a small company that wants to be great needs to have that special something, or “mojo” as the book calls it.  And second, great companies are a direct manifestation of their founders.  To be sure, there are a lot of great entrepreneurs whose companies fail, but the great small companies all have owners who are passionate about what they do, exhibit great leadership, and strive to be customer focused and develop the mojo that helps their company succeed.

Small Giants is a book worth reading but maybe my expectations for the book were different than what the book actually turned out to be.

Gems I am Using: Acts as Taggable On

This is the first in a series of posts I am planning on writing on the different gems I am using for Atomic Leagues.  Atomic Leagues is written in Ruby on Rails (currently v3.2.11).

Recently I added tagging to the administrative part of Atomic Leagues to allow teams, leagues, and organizations to tag their games, events, news articles, and seasons.  I wasn’t sure how things were going to go but the Acts as Taggable On gem made it a snap.  This was one of those examples where everything you heard about Rails is true and it only takes minutes to get something awesome like tagging working across your entire site.

Literally, the only things I had to do to integrate it into the site were to declare it on the models I needed to tag using:

 Rails |  copy code |? 
01
class Item < ActiveRecord::Base
02
  #Item owns all of the tags.
03
  acts_as_tagger
04
end
05
 
06
class Event < ActiveRecord::Base
07
  #Events can be tagged.
08
  acts_as_taggable_on :tags
09
  #Holds the tags on the page.
10
  attr_accessor :tags_input
11
end
12

Then to set tags with item as the owner I just had to do

 Rails |  copy code |? 
1
@item.tag(@event, :with => @event.tags_input, :on => :tags)
2

That’s it on the back end, but what about the front?  I used the tag-it jquery plugin, which rocked.

Book Review of Insanely Simple: The Obsession That Drives Apple’s Success

I first heard about Insanely Simple: The Obsession That Drives Apple’s Success by Ken Segall through a blog post on Signal vs. Noise.  I’ve read the Steve Jobs biography and The Perfect Thing, about how the iPod was developed, so was looking forward to reading more about Apple’s culture and how they are able to do the great things they do.

I liked Insanely Simple for the most part, although I thought it did get long.  The first few sections were interesting, but then I felt like the book kept repeating itself.  Yes, things need to be kept simple.  Yes, complexity is the root of all evil.  I got it.  I did think it was informative how the author kept bringing up counter-examples of companies thinking simply only to be caught in the complexity trap.  How many times have I set out to do something quick and easy only to get mired in the complex details?

My favorite chapters were Think Brutal, Think Small, Think Minimal, Think War, and Think Different.  They seemed to have the most relevant information.  Chapters such as Think Motion, Think Iconic, Think Phrasal, Think Casual, and Think Human I started skimming though.  I wasn’t as into the advertising segments of the book as much as I thought I would be.

Overall, Insanely Simple was a decent read.  It probably could have used some trimming, but was an interesting perspective by Segall.  He had a great window into Apple, both the years with and without Jobs, so was able to compare the different time periods.

Bizarre IE 9 behavior with ajax and jQuery

I have a page on Atomic Leagues that lets teams and leagues import their season statistics using a CSV file instead of manually entering them.  Everything works well this process and I think it will be a big benefit to those teams and leagues with a lot of historical data, but I ran into a really strange IE error when I was cleaning things up and disabling the submit button after it has been clicked.

My import process works like this:

  • The user specifies the CSV file to upload and clicks the upload button.
  • Using webtoolkit’s ajax file upload script (I’ve used this script in many different places and it always works great) I upload the file and parse it dynamically.
  • The action that handles the file upload returns html including the form with the submit button that I want to disable when clicked.
  • On the response callback of the upload script I do some simple jQuery to add a click event to the submit button to display a message “Data is importing…” and disable the button when it is clicked.

That is really all I am doing, pretty basic.  This worked fine in Chrome and Firefox but I could not figure out why it wouldn’t work in IE.  The click event on the button worked and the message would display but the form would never submit.

Finally I figured it out.  The solution?  Previously when I returned the html the form element was the first element.

[code]

<form id=”my-form”>

</form>

[/code]

For some reason IE wouldn’t let me select the form element using jQuery because it was the first element.  When I changed the response to wrap the form in a meaningless div so it isn’t the first element, everything works fine.

[code]

<div>

<form id=”my-form”>

</form>

</div>

[/code]

jQuery Mobile and jQuery UI don’t mix (or do they?)

I’ve had a mobile version of Atomic Leagues for at least a few years but it isn’t all that great so I’m in the process of rebuilding the mobile version using jQuery Mobile.

My goal is for Atomic Leagues to be as responsive as possible and to reuse as much of the existing code as I can. Fortunately, because Rails enforces an MVC pattern things are set up to do exactly that.

Although my early impressions of jQuery Mobile are very favorable (at some point I’ll post a full summary of why I went with jQuery Mobile vs. some of the other mobile frameworks out there), one thing I have noticed already is that jQuery Mobile and jQuery UI don’t get along well together.

In Atomic Leagues, when a user is adding an event I am using jQuery UI for the datepicker (for those browsers that don’t support the html 5 date input type) and reusing the same view in the mobile site throws an ugly exception:

a.widget.extend is not a function

It turns out that the jQuery Mobile and jQuery UI libraries can’t exist together. Looking into this further I came upon a number of articles talking about the same issue. Here is one: http://forum.jquery.com/topic/reconciling-jquery-ui-and-jquery-mobile

Most of the recommendations seemed to be to pick one library or the other, potentially not a great answer for those looking to be as responsive as possible. I am using some server side detection of mobile user-agents to get a feel for whether the user is mobile and I am now using this to also decide which library (jQuery Mobile or jQuery UI) to include on a page. Maybe not a foolproof solution but one that is working for me.

UPDATE: There still may be issues when using jQuery Mobile and jQuery UI on the same page but if you make sure to:
1. Load jQuery
2. Load jQuery UI
3. Load jQuery Mobile

It then seems to like things better.

Book Review of Head First Mobile Web

I had been looking for a new book on mobile web development and stumbled across Head First Mobile Web by Lyza Danger Gardner and Jason Grigsby.  After finishing the book I was surprised at the breadth of subjects it covered, they really did walk readers through almost every aspect of mobile web development.

I’ll admit that my main reason for reading the book initially was for the sections on responsive web design but was happy to also read about mobile web frameworks including jQuery Mobile, device detection, local storage, using PhoneGap, and more.

Responsive web design to me is a mixed bag, I see the power behind the concept but the developer in me throws up red flags when building pages based on media queries alone.  Sure, it would be great to leave the server side alone and alter the presentation based on the size of the user’s browser but is that something that can be done efficiently?  To me responsive design is great for content heavy or informational websites but less mature for web apps.  I cringe at building out components server side or making a database call only to have the presentation layer throw it away because of responsive design.  I’m a developer – performance, processing speed, and memory matter.

The other biggest impression that struck me while reading this book is that responsive design is great in theory but implementing it for a wide variety of devices can be a major headache and involves a fair amount of hacks.  CSS in general has always felt that way to me as it isn’t a programming language but feels like it should be.  Responsive design doesn’t eliminate the need for browser checks, etc.  Anyone that has worked with javascript long enough can remember what it was like to write browser specific code and the nightmare it was to debug across the various browsers of the time.  Then jQuery came along and changed all that, now it is rarely an issue.  I’m still waiting for a framework to come along with CSS in the same vein, to eliminate browser idiosyncrasies.  It would go a long way towards simplifying responsive design as well.

Don’t get me wrong, responsive web design is a great concept and is here to stay, I just think it might eventually migrate to becoming a hybrid of responsive design on the front-end and server-side detection on the back.

The PhoneGap section was interesting.  I think as the mobile market continues to fragment (if Windows 8 catches on once it is released) a need for a single development platform that can build apps for any device will become even more important.  Already most smaller businesses cannot afford separate development efforts for Android and iOS.  PhoneGap helps address that by allowing developers to use HTML 5 and a mobile framework such as jQuery Mobile or Sencha Touch to build hybrid apps.  Again, in theory, it would be possible to build a responsive HTML 5 website and wrap it in PhoneGap to make it an app.  An interesting idea, although I’m not too crazy that they run as web views on devices instead of with native UI components.  As web views become faster that issue may go away.  Other similar technologies such as Appcelerator Titanium allow developers to build a cross-platform mobile app using Javascript and native UI components, so the need is definitely there.

Head First Mobile Web is definitely worth reading if you want a broad introduction to mobile web design and development.  It brings up many interesting points and gives the reader a lot to think about.  I also thought the book did an excellent job of trying to steer readers towards best practices and really did dive into the details on the lot of the topics discussed.

 

Book Review of Designing the Obvious

I really enjoyed Designing the Obvious: A Common Sense Approach to Web & Mobile Design by Robert Hoekman, jr.  Even though I’ve read a large number of design and UI book over the years, I always find something new and interesting in every book I read.

The big ideas for me from this book were:

  • Good defaults – don’t make the user work harder than they have to, default what you can so they don’t even have to think about what to enter.  If they need to change it, they will.
  • Forgiving software – users make mistakes, make sure your software is forgiving enough to allow them to recover.  Or better yet, don’t allow them to make mistakes in the first place by using good defaults and helpful error messages.
  • Be persuasive – Know what your motivation is and follow your original vision.  I’m as guilty as not following this as anyone, sometimes it seems like there is a feature you just know your users will love, so you add it whether it really is consistent with what you are trying to do or not.  For my Atomic Leagues site it is a constant give and take on this one as my vision is to create the best statistics-based sports websites out there, but it still has to have enough other functionality to make it useful for teams to use outside of the stats part of it.
  • Don’t innovate, elevate – You don’t always have to reinvent the wheel.  If you see an example of something that works, there isn’t any reason why you need to do something completely different.  Do the same thing or maybe use it as a model and tweak it slightly to fit better with what you are trying to accomplish.

I would say that although the book has mobile in the title, the mobile guidelines are a little weak, almost like an afterthought.  In general, when designing for mobile I think stick to the idea that less is more (less options, less navigation, keep only core functionality).

Designing the Obvious is an interesting, thought-provoking, and interesting read.  I would definitely recommend it to anyone interested in learning more about web and mobile design.

eCheck UI on Payment Forms

On my Atomic Leagues site I process online registrations for teams and organizations.  Previously that was only through credit cards but recently I rolled out the ability for users to pay with e-checks (which takes the charge out of their savings or checking account instead of their credit card).

I wasn’t able to find a lot of good examples of e-check processing on the web so I thought I would offer up my solution as an example.  Essentially I have two different views of the billing form on my checkout page, one for e-checks and one for credit cards.  The radio buttons toggle between the two views.  E-check is defaulted as I wanted to encourage people to pay with an e-check.  This does carry more risk from my stand point, as the funds aren’t verified real-time as with a credit card, but the processing fee overall is lower and will save teams and organizations money.

On the e-check payment form I validate that the bank routing number is 9 digits (and the payment gateway verifies it is a routing number for an actual bank) but beyond that there isn’t a lot of validation that can be done, which is kind of scary.

Selecting the credit card radio button displays the credit card fields.  Credit cards can be validated much more stringently and the funds are authorized at the time of payment, reducing risk considerably.

Has anyone else seen good examples of e-check user interface designs?  I’d be curious to hear of any more.

InvalidAuthenticityToken because of domain mismatch

On my team and organization create pages for Atomic Leagues I have an option where you can sign in with an existing account instead of creating a new one.  The link opens an overlay that allows the user to sign in using their email and password and then closes back to the create page.  Both the create and sign in forms are ssl.

Initially when clicking the sign in link the ajax response was a 422 (Unprocessable Entity), which I had never even heard of before.  Fortunately, the author’s solution in the 422 description (disable protect_from_forgery for the action in question) wasn’t something I had to do.

Turned out I had a domain mismatch in that for some reason I was manually building the url of the sign in ajax request and using that to submit the page.

I was displaying the page at http://atomicleagues.com/team/create, but the manual url creation was building it at http://www.atomicleagues.com/signin/lite and the authenticity tokens weren’t matching up.

[code lang=”rails”]

#Only SSL in environments other than development.
if (Rails.env.development?) then
lSubmitUrl = “http://”
else
lSubmitUrl = “https://”
end

lSubmitUrl = lSubmitUrl + MAIN_HOST + “/admin/signin/light”

[/code]

Looking at the code it didn’t make sense why I was manually building the url, so I just took it out and everything works as it should.  One of those things that seemed like it was needed at the time but wasn’t really needed at all and just ended up causing problems later.