Fork me on GitHub

Tagged: dev RSS

  • britg 10:10 pm on June 21, 2011 Permalink | Log in to leave a Comment
    Tags: dev,   

    New Relic Menu Bar Performance Monitoring App 

    New Relic has quickly become an invaluable tool for monitoring performance of Key Ring for me. I found myself constantly checking the dashboard, partly for the graph, but mostly for the quick metrics at the top. Namely, I pay the most attention to requests-per-minute, response time, and errors.

    Why keep a browser window dedicated to this? Fortunately, New Relic provides an API, so I whipped together a quick and dirty menu bars app to display the stuff I care about. Here’s what it looks like:

    If you’d find this useful, feel free to download the app here.

    Warning: The app is very simple. It prompts you for your New Relic API key and then loads your first Account and first Application. Perfect for my needs, but I’m open to suggestions. Do a lot of you have multiple accounts or applications? If so, I can add an account/application selector.

    Update: I’ve added support for multiple accounts and applications. Get the new version here!

    Feel free to contact me a brit at britg dot com with suggestions or feature requests!

     
    • Diego Plentz 2:03 pm on June 22, 2011 Permalink

      Put it on github :)

    • Diego Plentz 2:03 pm on June 22, 2011 Permalink

      Put it on github :)

    • Diego Plentz 2:04 pm on June 22, 2011 Permalink

      Put it on github :)

    • Diego Plentz 2:04 pm on June 22, 2011 Permalink

      Put it on github :)

    • britg 2:43 pm on June 22, 2011 Permalink

      Thanks! I’m planning to add a few more features and put it on the Mac App Store. If that doesn’t work out, I’ll share it on github for sure. In the mean time,  you can check out this older project that’s open source: https://github.com/crossforward/rpm-status

    • britg 2:43 pm on June 22, 2011 Permalink

      Thanks! I’m planning to add a few more features and put it on the Mac App Store. If that doesn’t work out, I’ll share it on github for sure. In the mean time,  you can check out this older project that’s open source: https://github.com/crossforward/rpm-status

    • Christophe Porteneuve 3:49 pm on June 30, 2011 Permalink

      Hey Brit,

      Excellent stuff. However, IMHE most people using RPM monitor multiple apps indeed, so an app/host selector would be a top requirement (I, for one, monitor 25+ apps across 3 accounts).

    • Christophe Porteneuve 3:49 pm on June 30, 2011 Permalink

      Hey Brit,

      Excellent stuff. However, IMHE most people using RPM monitor multiple apps indeed, so an app/host selector would be a top requirement (I, for one, monitor 25+ apps across 3 accounts).

    • Gerred 4:37 pm on June 30, 2011 Permalink

      I’d love multiple accounts.

    • Gerred 4:37 pm on June 30, 2011 Permalink

      I’d love multiple accounts.

    • Steve Shapero 5:41 pm on June 30, 2011 Permalink

      looks cool – os x 10.6+ only?

    • Steve Shapero 5:41 pm on June 30, 2011 Permalink

      looks cool – os x 10.6+ only?

    • britg 1:19 am on July 1, 2011 Permalink

      Thanks! Ok, good to know. I’ll work on multiple account management next!

    • britg 1:19 am on July 1, 2011 Permalink

      Thanks! Ok, good to know. I’ll work on multiple account management next!

    • britg 1:20 am on July 1, 2011 Permalink

      I don’t know, as I’m only running 10.6 — Let me know if you’re running something else and it doesn’t work.

    • britg 1:20 am on July 1, 2011 Permalink

      I don’t know, as I’m only running 10.6 — Let me know if you’re running something else and it doesn’t work.

    • Marshall Yount 4:22 pm on July 1, 2011 Permalink

      Dead sexy!

    • whatafy 12:45 pm on July 8, 2011 Permalink

      Very cool, thanks! 

    • Manoj Kumar 3:36 am on October 28, 2011 Permalink

      Muay Thai gear for training purposes, you may want to consider MMA
      equipment instead. It does not matter if you are studying Krav Maga,
      Kick Boxing, Judo, Karate or Jiu Jitsu the world of mixed martial arts
      have given us big benefits.muay thai training in thailand
       

    • Web design London 7:21 pm on December 29, 2011 Permalink

      I’m planning to add a few more features and put it on the Mac App Store. If that doesn’t work out, I’ll share it on github for sure.

    • Kids Summer Camp 6:52 pm on March 23, 2012 Permalink

      I love it! Great job!

  • britg 8:35 pm on June 17, 2011 Permalink | Log in to leave a Comment
    Tags: dev, ,   

    Complex Gesture Recognition in iOS – Part 2: The iOS Implementation 

    Well, it took a little longer than I had hoped, but I finally got around to implementing the N-Dollar Gesture Recognizer in Objective-C for iOS. If you remember, this all started with a need for an iOS implemenation of a good multi-stroke gesture (I call them glyphs) recognizer. N-Dollar was the clear winner in my research, so without further ado I present my attempt at implementing it.

    MultistrokeGestureRecognizer-iOS

    Grab the source here…

    To summarize how to use this library in a few bullet points:

    • Initialize a Detector and seed it with templates to the gestures you want to recognize
    • Capture user-input and pass it to the Detector
    • When you’re ready to detect the gesture, ask the Detector to calculate which of its templates the user input matches the most.

    Initializing the Detector

    Initializing the detector is a simple affair:

    It’s important to note that the detector is pretty useless unless you seed it with some templates to match against. Here I add a template of a gesture with [glyphDetector addGlyphFromJSON:].

    The JSON representation of these gestures are simply arrays of X,Y coordinate points. For instance, here’s a JSON array-of-points of a gesture that resembles the letter ‘D’. You can choose to use multiple strokes, or a single stroke with all of the points combined. Honey badger The detector doesn’t care!

    Capturing User Input

    It’s really up to you how you want to capture the user input. The UIResponder Class is a good start, but I’m personally using Cocos2d, so the following code makes use of their abstraction of touch events:

    Note that at each firing of the touch event handler, I take the corresponding point and add it to the recognizer through the [glyphDetector addPoint:] message.

    Detect the Glyph

    Once you’re satisfied with the user input, you can call [glyphDetector detectGlyph]. This will use the N-Dollar/Protractor algorithm to compare the user input with the templates you defined. For each template, the detector determines a score — higher is better. It’ll return the pre-defined gesture with the highest score to its delegate and from there it’s up to you whether to trust the match, or wait for more user input!

    Update: Here’s more info on interpreting the score that’s returned.

    Up Next, An App

    Don’t expect it any time soon, but I hope to put together an example app that demonstrates this library in its entirety. Please feel free to contact me at brit (at) this domain with any questions, or just shoot me a message on the GitHub repo!

     
    • Hjkhgk 12:45 pm on August 8, 2011 Permalink

      hjkhjgkhk

    • Moosc123 3:04 pm on October 1, 2011 Permalink

      Hi,
      Great work, and thanks for the tutorial!!
      Any chance to get an iphone app implementing this library?

      Thanks

    • britg 5:37 pm on October 1, 2011 Permalink

      Thanks! I’ve got an app in the works but it’s slow going. I hope to have it done soon, and I’ll definitely make a post about it.

    • Moosc123 9:55 am on October 2, 2011 Permalink

      Woww, great news !

      I hope this application will be open source…

      Thanks for your work !!

    • Schiesty 6:52 pm on October 2, 2011 Permalink

      Hi, I’m so happy I found your site.  I looked at N$ about a year ago but couldn’t find an objective c implementation.  One question, whats the best way to create these JSON template files?  Specifically I plan to be creating template files for characters “a, b, c, etc…”

      Thanks again!

    • TheiOSDev 8:58 am on October 7, 2011 Permalink

      @ Schiesty Have you find a way to create the JSON template files?

    • Web design London 11:06 am on November 5, 2011 Permalink

      Woww, great news !

    • nicoz_88 5:15 pm on November 26, 2011 Permalink

      Hi! Thank you for your work. I’m trying to use the WTMGlyphDetector in my own cocos2d Project and I’m experiencing some difficulties. I don’t know how to correctly import your library in my project. I’ve added the .xcodeproj file to my project and added WTMGlyph library in target dependencies of my project and then added to it the header search path for WTMGlyph files. When I import “WTMGlyphDetector.h” and when I set a property for my class variable WTMGlyphDetector all works fine. But when I write glyphDetector = [WTMGlyphDetector detector] as you suggest in the init method xcode returns a linker error: “Undefined symbols for architecture i386:

        “_OBJC_CLASS_$_WTMGlyphDetector”, referenced from:”.
      Can you explain me what I’m doing wrong? Thank you.

    • nicoz_88 7:24 pm on November 26, 2011 Permalink

      i was forgetting to link in the project setting the framework libWTM.a.
      Now all is working.

    • eminc 7:19 pm on January 25, 2012 Permalink

      Looks like an old comment but…
      I print the touch location to the debug console whenever the touch begins, moves and ends. Then I manually copy/paste it to a text editor…

      When touch begins:
          printf(“[ [%d,%d]“,(int)(touchLocation.x), ((int) touchLocation.y));

      When touch moves:
          printf(“,[%d,%d]“,(int)(touchLocation.x), ((int)touchLocation.y));

      When touch ends:
          printf(“,[%d,%d] ],n”,(int)(touchlocation.x), ((int)touchlocation.y));
      (as you see this is c++, but you get the idea)

    • Guest 4:45 pm on February 17, 2012 Permalink

    • Raja I 8:30 am on March 14, 2012 Permalink

      hi thank u for the implementation file,so please send me with example app its very useful for all..

       

  • britg 10:03 pm on June 2, 2011 Permalink | Log in to leave a Comment
    Tags: dev   

    Using Foreman for Logging and Watchr 

    Foreman has quickly turned into a must-have gem for local development for me.

    From @ddollar’s description of Foreman:

    Using foreman you can declare the various processes that are needed to run your application using a Procfile.

    Besides the normal processes (rails, workers, etc.) I’ve found great success running log tailing and watchr through Foreman. Here’s what my current Procfile looks like:


    (View original to see this Gist.)

    If your development pattern is anything like mine, it looks like:

    • Edit a test, model or controller: check watchr output

    • Edit a view, js or scss file: refresh the browser

    Here’s what that looks like through Foreman:

    This works well with watchr and log tailing output, as they rarely overlap. Even if they do, finding the appropriate output is easy with Foreman’s prepending of the process name and timestamp.

    Have any other tips/tricks with Foreman? Let me know!

     
  • britg 1:32 pm on May 14, 2011 Permalink | Log in to leave a Comment
    Tags: dev, ,   

    Complex Gesture Recognition in iOS – Part 1: The Research 

    This Ain’t No 3-Finger Swipe

    Given that touch-based input has become a staple of mobile devices, I was surprised to find a dearth of good, open source complex gesture recognition libraries in the wild.

    Well, maybe I should explain what I’m referring to when I say, “complex gesture.” I’m not talking about the swipes and pinches that dominate our current interactions with touch devices. I’m more interested in what I like to call “glyphs” – a series of strokes that form a symbol.

    A good example of what I consider a glyph is something like a letter in the alphabet. A ‘Q’ glyph is the circle stroke and the southeast stroke positioned in such a way that it’s recognizable. But, OCR is not quite what I’m looking for because it’s specific to text. The ideal solution should also recognize abstract glyphs — symbols that aren’t hard coded into a lookup dictionary.

    Psh, I Can Write That

    Like all foolhardy, naive developers, I initially tried to just wing it. Research shmeshmearch. This would be easy — just take user input, break it down into individual strokes and then compare the input to a template for a glyph.

    Here are the primary challenges I ran in to while trying to implement this approach:

    • Users don’t draw well, especially with their fingers — lots of variance.
    • The touch events trigger at a pre-determined interval — fast strokes lead to fewer data points.
    • You can create single stroke gestures with multiple strokes and vice versa — i.e. a checkmark can be made with two strokes or one fluid motion.
    • There are multiple permutations for a given stroke as shown below, hand drawn by me for your enjoyment.


    Just some of the stroke combinations to create a ‘Q’

    I spent a few hours hacking away at different solutions to these problems, but ultimately decided this sub-stroke comparison approach wasn’t going to cut it.

    Step 1 Should Always Be “Search Google For Some Context”

    I found two projects that attempt to approach recognition the same way I had — sub-stroke combinations:

    Ultimately, like my approach they were too limiting and didn’t address key issues. Both allowed for abstract gestures, but in testing they didn’t allow for the variance you’d find in real-world user input scenarios.

    Then, I stumbled on the 1-Dollar Recognizer. Its unique way of comparing input to a pre-defined template (more on this later) made it very good at error correcting, and it’s order/direction agnostic. But, unfortunately it’s also uni-stroke only. The user would have to make one continuous stroke to ensure recognition. Close, but not quite there.

    N Dollar Baby

    Fortunately, the same group who developed 1-Dollar extended it to include multi-stroke detection and called it the N-Dollar Recognizer1.

    Multistroke? Check. Order and direction agnostic? Check. Error tolerant? Check. Fast and easy to implement? Check. High pun potential? Check. Well, N Dollar certainly has the biggest bang for the buck, but can it put its money where its mouth is?

    How The N Dollar Recognizer Works

    If you’re interested in the specifics, I recommend reading the N Dollar research paper. I’ll keep it high-level here.

    Error Correction

    N Dollar, and its predecessor 1 Dollar, both use the nearest neighbor approach to recognition. It compares user input to each of a set of pre-defined templates and gives each a score. The highest score wins if it is within a certain margin of error. This allows sub-strokes in a glyph to be sloppy, as long as the overall glyph is closest to the intended template.

    Data Points

    N Dollar creates a vector from all of the input points and interpolates additional points if necessary. Since sub-strokes are not as important in its algorithm, the final glyph just has to be closest to the intended template regardless of the number of data points.

    Multi-stroke vs Uni-stroke

    N Dollar doesn’t care how many strokes the user inputs to create a glyph. Before comparing against templates, all sub-strokes are connected into a uni-stroke. The illustration to the right (from the N Dollar limitations page) shows that although the user input two horizontal lines, N Dollar connected them before it ran its matching algorithm. This turns out to be one of N Dollar’s biggest limitations, but also the key to its speed and multi-stroke support. In my testing, this drawback was outweighed by N Dollar’s other factors.

    Order and Direction Dependency

    N Dollar calculates all the permutations of the generated uni-stroke before matching. The illustration below (taken from the research paper) shows how a user-drawn X gets defined 8 different ways regardless of the original input order. The comparison between the input and template is actually direction dependent, but N Dollar overcomes this by including all the possible directions in its calculation.

    There’s a lot more to N Dollar than what I describe above, and its authors are nothing short of brilliant. Playing with the javascript implementation, I’m amazed at how quickly and accurately it’s able to calculate and compare even the most complex glyphs I throw at it.

    Knowledge is Half the Battle

    Implementation is the other half. That’s how that goes, right? I’ve started a basic iOS implementation here (the original is in javascript), and once I finish I’ll put together a summary in part 2 of this series. Stay tuned!

    Update: I’ve finished the implementation here. Read about it here

    ———-

    1 Anthony, L. and Wobbrock, J.O. (2010). A lightweight multistroke recognizer for user interface prototypes. Proceedings of Graphics Interface (GI ’10). Ottawa, Ontario (May 31-June 2, 2010). Toronto, Ontario: Canadian Information Processing Society, pp. 245-252.

     
  • britg 8:26 pm on May 11, 2011 Permalink | Log in to leave a Comment
    Tags: dev   

    The Ratings Solicitation 

    Recently Marco Arment wrote a post and a comment on Twitter about his feelings on the seemingly ubiquitous ratings solicitation in iOS apps:


    If I ever added a rating solicitation in Instapaper, it’d be buried in the Settings screen somewhere. But I still probably wouldn’t.less than a minute ago via Twitter for Mac

    Believe me, I understand his reluctancy because I felt it too. If you had asked me two months ago what I thought users think about these, I’d say they thought it was spammy, obtrusive, and just plain shady. But then I found myself implementing it in Key Ring in our latest update. Oh, how my feelings have changed.

    The Vocal Minority

    I’ve heard that review systems tend to expose the vocal minority, and I believe this. It doesn’t matter if it’s Amazon or iTunes, the vast majority of people who are satisfied, or heaven forbid happy, with a product will never take the time to write a review or leave a rating.

    But, there’s a small and extremely motivated group of people that are willing, nay eager, to sling around 1-star reviews at the slightest hint of inconvenience. They have a forum, and by God they will use it. This affects the sleep patterns of app developers in ways I never fathomed until I became one.

    The Lazy, Content Majority

    The ratings solicitation is the app developers’ last bastion of defense against the Vocal Minority. Key Ring was a meh-inducing 3 stars for the first year of its existence, and our reviews were pretty evenly dispersed between 1 star and 5 stars. After implementing a very unobtrusive, one-time, opt-in ratings solicitation, magically Key Ring is now a sturdy 4.5 stars! The 5 star ratings are through the roof.

    Oh how I wish I could attribute the dramatic change to the new UI, speed improvements, or something else I could brag about. Nope, if you look at the written reviews for Key Ring it becomes obvious that the users who are content with the app (who would never give a second thought to rating or reviewing it) are blurting a few words of praise and tapping that last star on the far right just because the app happened to remind them, in a moment of whimsical curiousity and boredom, that iTunes has this rating system and using it might be slightly less boring than whatever they are doing.

    The surprising thing is, we have not once had a single complaint or mention about the ratings solicitation. Hell, we get notified by users when we mispell words in our Terms of Service!

    The Bottom Line

    There are people out there who are completely satisfied with whatever you’re producing, but you’ve probably never heard from them. In an ecosystem that values the coveted “rating” so very dearly, a tactful solicitation for a review is a great way to expose your fans and let potential users of your app know that it is worthwhile. Don’t be afraid to implement one, and don’t think less of apps that do.

     
    • website coder 7:58 am on May 13, 2011 Permalink

       Yeah its correct.. This review is the great way to expose our fans.. Thanks for this information..

  • britg 12:07 pm on January 10, 2010 Permalink | Log in to leave a Comment
    Tags: dev, , webgl,   

    Quick Look: WebGL and Web Sockets 

    The internet is still a very young ecosystem of immature techn… Woah, the BS meter pegged there for a second. Forget the pontification, let me just spit out the two technologies that get me excited about billing myself as a Web Developer.

    WebGL

    This is a new spec that’s being developed by the Khronos Group (the group behind OpenGL) to expose OpenGL to browsers through the canvas element.

    Why is it exciting? Three words: Javascript. Hardware. Acceleration. Damn, I need three more: In. The. Browser.

    The concepts should speak for themselves, but if you still need some convincing follow the steps below and be sure to take a look at your CPU usage while running these demos. (Hint: CPU usage will be very low because you’re riding your GPU).

    • Grab the latest nighly of Chromium here if you are not already running it.
    • Start Chromium via the command line:
      • Windows: chrome.exe --no-sandbox --enable-webgl
      • OSX: Chromium.app/Contents/MacOS/Chromium --no-sandbox --enable-webgl
      • Linux: ./chrome --no-sandbox --enable-webgl
    • Follow this link to some examples of WebGL in action.

    Again, check your CPU usage while running the demos. It should be very low (if you have a GPU) as the demos should be hardware accelerated.

    Web Sockets

    Comet? Long-Polling? Forever Frame? In two years we will all be sitting around a trash barrel fire laughing about the days of yore when we had to use such hacks.

    Why are we huddled around a trash barrel fire? Because it’s post-apocolyptic New Zealand, the last bastion of humanity. Anyways, that’s another “In This Decade” blog post…

    From websockets.org:

    [The Web Socket Interface] defines a full-duplex communications channel that operates over a single socket and is exposed via a JavaScript interface in compliant browsers

    Here’s the spec in case you want to read it… haha, me neither.

    Again, the concept here should speak for itself. Two-way communication with web servers in an easy-to-use interface.

    
    var websock = new WebSocket("ws://www.websocket.org");
    
    websock.onopen = function(evt) {
      console.log(evt)
      websock.send("Hello Web Socket!");
    };
    websock.onmessage = function(evt) {
      console.log(evt)
    };
    websock.onclose = function(evt) {
      console.log(evt)
    };
    websock.close();
    

    Fortunately, there are already many projects implementing the web sockets protocol. To name a few,

    One thing to note is that the web socket protocol will adhere to the cross-domain security restriction that XHR has. The good news is it will ship with support for server-side origin discretion using the same Origin headers in CORS.

    It’s all about the gaming, stupid

    I’m going to predict that in 2 years, we will see current A quality games developed in-browser ontop of these two technologies. Don’t get me wrong, AAA quality console and PC titles won’t be disrupted like the music and print industries any time soon. But, the “casual” label on browser games will go away.

    This is what has me really excited about being a web developer in this decade. Parity with desktop development is inching closer, and all ontop of open technologies.

    No plugins. No corporate owner.

    Win. Win.

     
    • peterlubbers 12:44 pm on January 11, 2010 Permalink

      Nice post! I'd like to add Kaazing WebSocket Gateway to the list of implementations. It's a production-ready WebSocket Gateway. The best part? It has emulation for all the older browsers (Anything other than Chrome right now), so you can already use WebSocket APIs today.

    • Pl4n3 3:12 pm on March 12, 2010 Permalink

      Nice posting! Games using WebGL and WebSockets is a nice perspective. I made a RTS-game demo using WebGL http://pl4n3.blogspot.com/2010/03/towards-webrt…, I also plan to integrate websockets for the multiplayer-part.

    • britg 3:38 pm on March 12, 2010 Permalink

      Hey Pl4n3 — awesome that you're working on an RTS in WebGL! Your demo throws an error in Webkit nightlies, though — “Error: 0:3: 'uniform' : cannot initialize this type of qualifier” (with wegGL enabled)

      Which browser are you recommending for the demo?

    • Pl4n3 4:09 pm on March 12, 2010 Permalink

      Thanks, also for the RT :) The RTS currently runs here with Firefox 3.7 (Minefield) nightly. Yesterdey it also worked with Chrome, but today WebGL could not initiate there, strange..

    • evilhackerdude 8:07 pm on March 16, 2010 Permalink

      Hey, I tried the RTS demo with the latest Minefield nightly (3.7pre4 I thin), yet I got exactly same error as Brit.

    • Pl4n3 3:34 am on March 17, 2010 Permalink

      Hi, i just updated Minfield to the latest version here (3.7a4pre), and the demo runs without problems. Currently cannot reproduce the error :/ Hopefully later, as WebGL gets more stable, this might resolve itself.

    • Lindsay Stanley Kay 5:08 am on July 2, 2010 Permalink

      Aha great post this, cheers, helps me get started here.

      Yes it seems that the WebGL framework hackers, having got things drawing, are rightfully turning their attention now to the backend. I just added Sockets to SceneJS as well: http://scenejs.wikispaces.com/SceneJS.Socket – early days – comments appreciated!

      Pl4n3 – whoah – looking forward to seeing how you implement the game logic/protocol etc! PS Your demo works good for me in Chromium build #51510

    • lingerie 12:09 am on August 20, 2010 Permalink

      It's so tough to encounter right information on the blog. I realy loved reading this post. It has strengthen my faith more. You all do such a great job at such Concepts… can't tell you how much I, for one appreciate all you do!

    • Arne Wieding 7:12 am on November 23, 2010 Permalink

      Nice post, however i think you are being very optimistic here. I think this will rather take 4-5 years instead of 2. Especially since your post in now roughly a year old and not much has changed, the next browser generation still hasnt arrived in a stable form.

      Furthermore id like to add that most modern games use UDP while WebSockets use TCP/IP which is not well suited for games. You might do some simple games with that, but any real time multiplayer games dont work that well.

      Still interesting tech, but it will take some more years to mature.

    • modern home design 10:06 am on February 13, 2011 Permalink

      It looks like webgl is more promising…

    • bouncy castles for sale 1:06 am on February 19, 2011 Permalink

      Great!This is awesome!Thank you!

    • web design london 8:36 pm on August 11, 2011 Permalink

      Nice posting! Games using WebGL and WebSockets is a nice perspective.

  • britg 10:46 am on December 29, 2009 Permalink | Log in to leave a Comment
    Tags: , dev, , , sinatra   

    Cross Origin Resource Sharing with Sinatra 

    It’s no lie that I think highly of the potential of Cross Origin Resource Sharing. One of the great things about it is that it doesn’t take much re-wiring of existing server (or client-side) apps to start working cross domain.

    Enabling your server app is as simple as including a few extra headers when you detect a cross origin request. How do you know it’s a cross origin request? You’ll see the Origin: header — all CORS requests will have it. From there, response headers depend on the specifics of the request, but I won’t go over those here — check out the Mozilla Developer Center treatment for in-depth information.

    I’ve been working with Sinatra a lot lately, so I put together an extension for Sinatra that makes enabling Cross Origin requests even easier.

    sudo gem install sinatra-cross_origin

    There are two ways to use the extension: globally or per-route.

    Global

    For when you want to share all your endpoints cross-domain.

    
    require 'sinatra/base'
    require 'sinatra/cross_origin'
    
    class MyApp < Sinatra::Base
      register Sinatra::CrossOrigin
    
      enable cross_origin
    
      get '/' do
        "This is available to cross domain javascript requests automatically"
      end
    end
    

    Per Route

    For when you want to share only some of your routes cross-domain.

    
    require 'sinatra/base'
    require 'sinatra/cross_origin'
    
    class MyApp < Sinatra::Base
      register Sinatra::CrossOrigin
    
      get '/' do
        cross_origin
        "This is available to cross domain javascript requests"
      end
    end
    

    Configuration

    You can mix and match app-wide config and request specific config.

    
    require 'sinatra/base'
    require 'sinatra/cross_origin'
    
    class MyApp < Sinatra::Base
      register Sinatra::CrossOrigin
    
      configure do
        # Comma separate list of remote hosts that are allowed.
        # :any will allow any host
        set :allow_origin, :any
    
        # HTTP methods allowed
        set :allow_methods, [:get, :post]
    
        # Allow cookies to be sent with the requests
        set :allow_credentials, true
      end
    
      get '/' do
        # Only available to GET requests originating from
        # http://example.com.  No cookies allowed.
        cross_origin :allow_origin => 'http://example.com',
          :allow_methods => [:get],
          :allow_credentials => false
        "This is available to cross domain javascripts"
      end
    end
    

    Grab the source at Github: britg/sinatra-cross_origin.

     
    • escort services 9:19 am on March 1, 2011 Permalink

      Cross-origin resource sharing Sending messages is not the only solution for sharing information between different websites. The cross-origin resource sharing API loosens the controls over AJAX calls to anywhere but the home domain. …

    • Chris Castle 4:52 am on July 4, 2011 Permalink

      Hey Brit-  Thanks for putting this together.  I’m trying to make an HTTPS cross-domain request with Basic Auth.  I’m using Sinatra (obviously) on the server and jquery on the client.  I’m getting a 401 Unauthorized response from the server.  In looking at the Request headers I don’t see the browser sending the ‘Authorization’ header.  Here are the request and response headers.  Any idea what’s wrong?  If I hit the Request URL by itself in a browser, the auth box pops up, I enter my credentials, and everything works great — but not when it’s requested via javascript…

      Request URL:https://my.site.com/ec2/describe?env=dev&instanceId=i-b285d4dfRequest Method:GETStatus Code:401 UnauthorizedRequest HeadersAccept:*/*Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3Accept-Encoding:gzip,deflate,sdchAccept-Language:en-US,en;q=0.8Connection:keep-aliveHost:my.site.comOrigin:http://localhost:4567Referer:http://localhost:4567/index.htmlUser-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.41 Safari/535.1Query String Parametersenv:devinstanceId:i-b285d4dfResponse HeadersAccess-Control-Allow-Credentials:trueAccess-Control-Allow-Headers:AuthorizationAccess-Control-Allow-Methods:GET, POST, UPDATE, DELETE, OPTIONS, HEADAccess-Control-Allow-Origin:http://localhost:4567Access-Control-Max-Age:1728000Connection:keep-aliveContent-Length:15Content-Type:text/html;charset=utf-8Server:thin 1.2.11 codename Bat-Shit CrazyWWW-Authenticate:Basic realm=”Restricted Area”

  • britg 12:11 am on December 17, 2009 Permalink | Log in to leave a Comment
    Tags: dev, ,   

    Scriptstack – Organize and Share Javascripts 

    scriptstackI’ve been hacking on a small project in my free time that I uploaded today: scriptstack.

    What is scriptstack?

    Well, if you’re like me you probably have 4 or 5 javascript files you include in just about every new project or site your start. jQuery. Tooltips. Lightbox. qTip. Or, you just put together a nice portfolio site for a client and you want to save that specific set of javascript plugins for the next time you do something similar.

    Scriptstack aims to be an easy and social way to organize your “stacks” of scripts. You can:

    • Upload scripts.
    • Click and drag them into the order they should be loaded in the browser.
    • Tag them with a few keywords to make them indexable for future search.
    • Download the concatenated stack in minified or raw format.

    That’s about it for now, haha. Release early, release often, right? I should note that there’s no permissions on the stacks. If you create one, it’s editable by anyone right now. I plan to add User accounts and ownership soon.

    Warning: the site probably only works in Firefox.

    Under the hood

    I took this opportunity to expand my horizons as far as the technology under the hood. I’ll go in-depth on these as I continue to develop, but a quick rundown of the tech stack (pun intended but probably shouldn’t be):

    I also open sourced all the code that runs the site here incase you are interested in what poorly written Ruby looks like.

    If you happen to check it out, let me know what you think! And as I said, I will expand on different parts of it here in the near future, so stay tuned.

     
  • britg 11:17 pm on December 11, 2009 Permalink | Log in to leave a Comment
    Tags: ajax upload, dev, , jsonview   

    Ajax Uploading Plus JSON Response Plus JSONView = Disaster 

    So, I’ve spend the last few hours debugging what seemed to be a tear in the fabric of the universe. I’m working this excellent javascript library, AjaxUpload, that, as the name implies, creates a no-pageload form upload. It’s easy to implement and makes an upload infinitely more usable in my opinion; definitely check it out.

    The upload works by pointing the target attribute of a multipart form at a hidden iframe. When the iframe updates with the results of the upload, an event listener reports the response to the parent page, and voila — you have an upload without a page refresh.

    The only problem with this iframe approach is that your response is being fully rendered by the browser instead of passed in the response body of an XMLHttpRequest like most ajax interactions. Combine this with a server-side upload script that returns JSON and here’s where the fun starts.

    If you’re using the JSONView Firefox plugin (and why the hell aren’t you!?) the JSON gets rendered with some wrapper html and styling to create an interactive and human readable version of the JSON.

    See the problem here? What gets reported to your upload-complete event listener isn’t the original JSON, but the HTML-wrapped JSON. This can lead to what can only be described as multiple hours of FAIL in which you try and figure out why your JSON response can’t be parsed and used in your javascript.

     
    • DVD Duplicator 12:27 am on October 27, 2010 Permalink

      Thanks for sharing your experience.

    • philbocq 10:53 am on December 3, 2011 Permalink

      I encountered the same problem, however you can change the header response from application/json to text/html so jsonview doesn’t detect the returned page as json and ajaxUpload works

  • britg 11:02 am on December 10, 2009 Permalink | Log in to leave a Comment
    Tags: , dev, ,   

    On Stack Overflow Careers 

    If you’re not familiar with Stack Overflow Careers, check out Introducing Stack Overflow Careers and Stack Overflow Careers: Amplifying Your Awesome.

    In short, it aims to build a for-pay CV hosting and searching service on top of the success of Stack Overflow.

    stackoverflow I have mixed feelings about Stack Overflow Careers.

    No, I’m not questioning whether or not they should have built it, or whether or not they should charge money for it. I have no problem with Joel or Jeff using their interweb fame to make a buck like this guy seems to (Clarification: William’s beef isn’t with the for-pay aspect, but with the underlying system itself. See first comment.). If they want to, they should.

    America++!

    My quandary is whether I should make an effort to participate in Stack Overflow and Careers. I like the site and use it daily, but I don’t actually participate. I am a consumer, not a contributor. Should I eschew my natural introverted tendencies and force myself to contribute?

    Maybe

    The Stack Overflow group of programmers seem to “get it.” On the whole they are smart, pragmatic, and can communicate in complete sentences (skills listed in reverse order of importance).

    As a freelance programmer, I would like to be attributed with those qualities when looking for work. That’s the true value in associating a job search with Stack Overflow and is the reason why they can charge programmers to list their CV. If you’re recognized as a member of that community, you’re much more valuable to job searchers that are Stack Overflow-aware.

    Maybe there’s some value in participating in the site and quantifying my association with the Stack Overflow type of programmer?

    Nah

    But, ultimately what am I trying to accomplish? Sure, I want to be known as a competent and gets-stuff-done kind of programmer. Stack Overflow is an avenue to quantify that I have these skills; it isn’t the method by which these skills are obtained.

    Joel Spolsky himself said,

    The great software developers, indeed, the best people in every field, are quite simply never on the market.

    He goes on to explain that if you’re a great developer, you’ll be recognized as such through your work.

    I think this says it all. I shouldn’t force myself to participate in a contrived system attempting to quantify competence. Don’t get me wrong, if you enjoy interacting and contributing to Stack Overflow, more power to you! But for me, if I’m doing the right things to further myself as a developer, the rest will take care of itself. More do-ey, less talk-ey.

     
    • wshields 11:30 am on December 10, 2009 Permalink

      Just to clarify, speaking as the author of the linked post: I don't have a problem with Jeff, Joel or anyone making a buck.

      It just crosses a line when a fatally flawed (imho) model is being sold on false promises.

      BTW, the theme for your blog is fantastic. WordPress? What theme?

    • britg 11:46 am on December 10, 2009 Permalink

      Thanks for clarifying. I'll update the post to point to your clarification.

      Glad you like the theme, but I can't really take any credit for it, haha. It's from Woothemes.com — Bueno: http://www.woothemes.com/2009/11/bueno/

c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
l
go to login
h
show/hide help
esc
cancel