{ Supportbee Dev Blog }
Stories from the developer bees

Mapping SupportBee's Users around the World

Our customers come from all around the world, as a matter of fact, they come from 79 different countries, and login to SupportBee almost everyday. So we had decided to share brief stories about our awesome users, and put up a page about them on SupportBee.com.

With just a little bit of programming, a little bit of Google Sheets and some Sketch design we created a rough map of where our users login from everyday.

Here are the steps we follwed to build the map:

1. Fetch the Last Login IPs of all the Users

This step is pretty simple, and straight forward. One of the most popular Rails authentication library - Devise, saves the current_sign_in_ip, and last_sign_in_ip in the User model. We mapped the last_sign_in_ip into an array.

2. Write a small script to fetch the Country for each IP

For this we wrote a small script, and used IP-API.com’s API to fetch the country for each IP, and exported that data into a CSV file. Below is the code for that.

require 'csv'
require 'faraday'

def fetch_and_export_countries
  filename = "tmp/country_data.csv"

  countries = {}
  ips = [192.168.1.2, 192.168.2.1, 192.168.12.14, 172.152.124.24, 66.24.21.22, 84.42.14.15, ...]
  ips.each_slice(140) do |slice|
    slice.each do |ip|
      Rails.logger.info "Fetching for #{ip}"
      
      response = connection.get do |req|
        req.url "http://ip-api.com/json/#{ip}"
      end

      body = JSON.parse(response.body)

      Rails.logger.info "#{ip} is from #{body["country"]} \n"
      if countries.has_key? body["country"]
        countries[body["country"]] += 1
      else
        countries[body["country"]] = 1
      end
    end

    # Requires sleeping because IP-API.com
    # only allows 150 requests per minute
    Rails.logger.info "Sleeping 1 minute ..."
    sleep 1.minute
  end

  CSV.open(filename, "wb") do |csv|
    countries.each do |item|
      csv << item
    end
  end

  Rails.logger.info "Done!"
end

def connection
  @conn ||= Faraday.new do |faraday|
    faraday.request  :url_encoded             # form-encode POST params
    faraday.response :logger                  # log requests to STDOUT
    faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
  end
end

We used the Faraday gem for making a HTTP call. The keys in the countries hash are all the countries, and values are the number of IPs from that country. IP-API.com only allows 150 requests per IP per minute for their free usage, so we put the process to sleep for 1 minute after every 140 IPs, keeping 10 as a buffer.

3. Create a GEO Chart with Google Sheets

Once we had the country data exported into a CSV file, we imported that into Google Sheets. Below is a screenshot of how the data looked. Using that we created a GEO Chart (also in the screenshot) of the number of users logging in from each country.

Google Chart

4. Create a good looking map using the data from Step 3

The last step was to refine the map created from GEO Chart, and create a simple map of where our Users login to SupportBee from. Following is the final map we created to use on the Customers Page.

SB World

read more »

Integrating Rails Simple Form with Semantic UI

While working on a complete UI redesign for SupportBee, we moved away from Bootstrap and decided to use Semantic UI. We loved Semantic UI because, besides being awesome, it offered UI components which helped us really speed up front-end development at SupportBee.

What is Semantic UI? It is a modern front-end development framework, just like Bootstrap and Foundation. According to their website, the goal of the framework is to empower designers and developers “by creating a language for sharing UI”.

Earlier, we were using Formtastic with Bootstrap, this setup was great a few years ago. The first natural step we took was to try and integrate Formtastic with Semantic, that did not workout very well because Formtastic adds a lot of extra markup to style its forms, and Semantic is very strict with markups.

So to keep our forms “simple”, we decided to move to Simple Form. The fact that Semantic is still young, these gems yet don’t offer native integrations with it. But, Simple Form has an easy to use Wrappers API to configure custom components.

Assuming that you have Semantic UI and Simple Form setup in your project, here is the Simple Form initializer to work with Semantic. Replace the code in config/initializers/simple_form.rb, with the code below.

# Use this setup block to configure all options available in SimpleForm.
SimpleForm.setup do |config|
  # Wrappers are used by the form builder to generate a
  # complete input. You can remove any component from the
  # wrapper, change the order or even add your own to the
  # stack. The options given below are used to wrap the
  # whole input.
  config.wrappers :default, class: :input, hint_class: :field_with_hint, error_class: :field_with_errors do |b|
    ## Extensions enabled by default
    # Any of these extensions can be disabled for a
    # given input by passing: `f.input EXTENSION_NAME => false`.
    # You can make any of these extensions optional by
    # renaming `b.use` to `b.optional`.

    # Determines whether to use HTML5 (:email, :url, ...)
    # and required attributes
    b.use :html5

    # Calculates placeholders automatically from I18n
    # You can also pass a string as f.input placeholder: "Placeholder"
    b.use :placeholder

    ## Optional extensions
    # They are disabled unless you pass `f.input EXTENSION_NAME => :lookup`
    # to the input. If so, they will retrieve the values from the model
    # if any exists. If you want to enable the lookup for any of those
    # extensions by default, you can change `b.optional` to `b.use`.

    # Calculates maxlength from length validations for string inputs
    b.optional :maxlength

    # Calculates pattern from format validations for string inputs
    b.optional :pattern

    # Calculates min and max from length validations for numeric inputs
    b.optional :min_max

    # Calculates readonly automatically from readonly attributes
    b.optional :readonly

    ## Inputs
    b.use :label_input
    b.use :hint,  wrap_with: { tag: :span, class: :hint }
    b.use :error, wrap_with: { tag: :span, class: :error }
  end

  # Custom Semantic Wrapper
  # Values are similar to the default wrapper above, with different classes
  config.wrappers :semantic, tag: 'div', class: "field", error_class: 'error', hint_class: 'with_hint' do |b|
    b.use :html5
    b.use :placeholder
    b.optional :maxlength
    b.optional :pattern
    b.optional :min_max
    b.use :label_input
    b.use :hint,  wrap_with: { tag: 'div', class: 'hint' }
    b.use :error, wrap_with: { tag: 'div', class: 'ui red pointing above label error' }
  end

  config.wrappers :ui_checkbox, tag: 'div', class: "field", error_class: 'error', hint_class: 'with_hint' do |b|
    b.use :html5
    b.wrapper tag: 'div', class: 'ui checkbox' do |input|
      input.use :label_input
      input.use :hint,  wrap_with: { tag: 'div', class: 'hint' }
    end
  end

  config.wrappers :ui_slider_checkbox, tag: 'div', class: "field", error_class: 'error', hint_class: 'with_hint' do |b|
    b.use :html5
    b.wrapper tag: 'div', class: 'ui slider checkbox' do |input|
      input.use :label_input
      input.use :hint,  wrap_with: { tag: 'div', class: 'hint' }
    end
  end

  config.wrappers :ui_toggle_checkbox, tag: 'div', class: "field", error_class: 'error', hint_class: 'with_hint' do |b|
    b.use :html5
    b.wrapper tag: 'div', class: 'ui toggle checkbox' do |input|
      input.use :label_input
      input.use :hint,  wrap_with: { tag: 'div', class: 'hint' }
    end
  end

  # The default wrapper to be used by the FormBuilder.
  # config.default_wrapper = :default
  config.default_wrapper = :semantic

  # Define the way to render check boxes / radio buttons with labels.
  # Defaults to :nested for bootstrap config.
  #   inline: input + label
  #   nested: label > input
  config.boolean_style = :inline

  # Default class for buttons
  config.button_class = 'ui primary submit button'

  # Method used to tidy up errors. Specify any Rails Array method.
  # :first lists the first message for each field.
  # Use :to_sentence to list all errors for each field.
  config.error_method = :first

  # Default tag used for error notification helper.
  config.error_notification_tag = :div

  # CSS class to add for error notification helper.
  config.error_notification_class = 'alert alert-error'

  # ID to add for error notification helper.
  # config.error_notification_id = nil

  # Series of attempts to detect a default label method for collection.
  # config.collection_label_methods = [ :to_label, :name, :title, :to_s ]

  # Series of attempts to detect a default value method for collection.
  # config.collection_value_methods = [ :id, :to_s ]

  # You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none.
  # config.collection_wrapper_tag = :div

  # You can define the class to use on all collection wrappers. Defaulting to none.
  # config.collection_wrapper_class = "field"

  # You can wrap each item in a collection of radio/check boxes with a tag,
  # defaulting to :span. Please note that when using :boolean_style = :nested,
  # SimpleForm will force this option to be a label.
  config.item_wrapper_tag = :div

  # You can define a class to use in all item wrappers. Defaulting to none.
  config.item_wrapper_class = 'ui checkbox'

  # How the label text should be generated altogether with the required text.
  # config.label_text = lambda { |label, required| "#{required} #{label}" }
  # Semantic UI has its own astrick
  config.label_text = lambda { |label, required| "#{label}" }

  # You can define the class to use on all labels. Default is nil.
  #config.label_class = 'control-label'

  # You can define the class to use on all forms. Default is simple_form.
  config.form_class = 'ui form'

  # You can define which elements should obtain additional classes
  # config.generate_additional_classes_for = [:wrapper, :label, :input]

  # Whether attributes are required by default (or not). Default is true.
  # config.required_by_default = true

  # Tell browsers whether to use the native HTML5 validations (novalidate form option).
  # These validations are enabled in SimpleForm's internal config but disabled by default
  # in this configuration, which is recommended due to some quirks from different browsers.
  # To stop SimpleForm from generating the novalidate option, enabling the HTML5 validations,
  # change this configuration to true.
  config.browser_validations = false

  # Collection of methods to detect if a file type was given.
  # config.file_methods = [ :mounted_as, :file?, :public_filename ]

  # Custom mappings for input types. This should be a hash containing a regexp
  # to match as key, and the input type that will be used when the field name
  # matches the regexp as value.
  # config.input_mappings = { /count/ => :integer }

  # Custom wrappers for input types. This should be a hash containing an input
  # type as key and the wrapper that will be used for all inputs with specified type.
  # config.wrapper_mappings = { string: :prepend }

  # Default priority for time_zone inputs.
  # config.time_zone_priority = nil

  # Default priority for country inputs.
  # config.country_priority = nil

  # When false, do not use translations for labels.
  # config.translate_labels = true

  # Automatically discover new inputs in Rails' autoload path.
  # config.inputs_discovery = true

  # Cache SimpleForm inputs discovery
  # config.cache_discovery = !Rails.env.development?

  # Default class for inputs
  # config.input_class = nil
end
read more »

Adding React to our stack

Backbone has been a game changer for SupportBee. However, time has made its limitations, when it comes to building views, very clear. We have a lot of code to hook data up to the views and we really wanted to get rid of it.

React has been on our radar since it launched and we recently added it to our stack. I am not going to discuss React since many have done that before much better than I could, check out this talk by Pete Hunt for example. Instead, this post will focus on how to make Coffeescript, Backbone.js and React play nicely.

Test drive your code

Yes, at SupportBee we test drive our code and we encourage you to do it too. Our examples will make use of Jasmine and Sinon.

Ready? Let’s start with a spec, I’ll call it ReactSpec.coffee.

describe "React dependencies", ->
  it "React should be defined", ->
    expect(React).toBeDefined()

  it "ReactDOM should be defined", ->
    expect(ReactDOM).toBeDefined()

  it "React addons should be defined", ->
    expect(React.addons).toBeDefined()

Run it and… watch it fail! How do we fix it?

Step 1: Rails Configuration

The React team provides a gem for using React in Rails. It also lets us use JSX and Coffeescript. Let’s add it to our Gemfile and run bundle install.

Note: Read carefully the documentation of the gem. Depending on the version you choose, you might need to download react files and put them into app/assets/javascript.

Run the test again. Does it fail?

Step 2: The Asset Pipeline

The asset pipeline requires you to add your assets in a manifest file, usually application.js. Now it should look like this

//= require jquery
//= require backbone
...
//= require react/react-with-addons
//= require react/react-dom

Run the test again. It passes! Congratulations! You have React set up.

Step 3: Create a React view

If you signup for a trial account in SupportBee you’ll see that, after you confirm your account, a modal will pop asking you to create an email address. This is how it looks.

Why don’t we recreate a bit of it? Start writing CreateEmailSpec.coffee.

describe 'CreateEmail', ->
  beforeEach ->
    @component = React.addons.TestUtils.renderIntoDocument Views.CreateEmail()

  afterEach ->
    ReactDOM.unmountComponentAtNode ReactDOM.findDOMNode(@component).parentNode

  it "should render with the correct DOM", ->
    renderedDOM = ReactDOM.findDOMNode(@component)

    expect(renderedDOM.tagName).toBe 'div'
    expect(renderedDOM.classList).toEqual(['container'])
    ...

Run it, watch it fail. Now let’s write our component CreateEmail.js.jsx.coffee.

CreateEmail = React.createClass(
  render: ->
    `<div className="container">
      <h2>Setup Your Email</h2>
      <p>You need to setup an email address and start forwarding your support
      emails to us.
      </p>
      <form>
        <input type="text" ref="email" />
        <input type="submit" value="Create Forwarding Address" />
      </form>
    </div>`
)

Views.CreateEmail = React.createFactory(CreateEmail)

Note: If you make use of JSX, don’t forget to name your React view files with the extension .js.jsx.coffee.

Meet Flux

React is great for views, but that’s it. Really. We won’t write an entire app with React alone. Backbone comes to the rescue. How do they relate? Facebook says “Lots of people use React as the V in MVC.” However they do not use the MVC architecture themeselves. Rather, Facebook introduced Flux. A detailed overview of this pattern is provided in its docs. You might also find interesting this cartoon guide. We’d love to hear your thoughts on Flux.

The short of it: Flux enforces a unidirectional data flow. Its major parts are the dispatcher, the stores and the views.

Let’s try it!

Step 4: Create a dispatcher

In Flux, every action is sent to all stores via the callbacks the stores register with the dispatcher. It has no logic. Your app should have a single dispatcher.

Facebook provides some utils including a dispatcher. Add it to our project the way we did with React before. Your ReactSpec.coffee should include this test

...
it "Flux should be defined", ->
  expect(Flux).toBeDefined()

Make sure it passes. Then create AppDispatcherSpec.coffee.

describe "AppDispatcher", ->
  it 'should be an instance of Flux.Dispatcher', ->
    expect(AppDispatcher instanceof Flux.Dispatcher).toBeTruthy()

Then AppDispatcher.coffee is as simple as this

SB.AppDispatcher = new Flux.Dispatcher

That’s it! We have a dispatcher.

Step 5: Create a store

A store registers itself with the dispatcher and provides it with a callback. Stores contain the application state and logic. Do you already have a place where you do that? Backbone models, perhaps? Right, Backbone models or collections can take the role of a Flux store! We just need to register a callback with the dispatcher.

In our use case, we want to add an email address. Given a Backbone model EmailAddress and a collection EmailAddresses, let us add a few lines to EmailAddressesSpec.coffee.

describe "EmailAddresses", ->
  ...
  it "should register a callback with the app dispatcher", ->
    expect(@collection.dispatchToken).not.toBe null

  it "should invoke registered callback on event", ->
    callback = sandbox.stub(@collection, 'dispatchCallback')
    payload =
      eventName: 'new-address'
      data: {}

    AppDispatcher.dispatch payload

    expect(callback).toHaveBeenCalledWith payload
    callback.restore()

To make it pass we need our EmailAddresses.coffee to look something like this

EmailAddresses = Backbone.Collection.extend
  initialize: ->
    @dispatchToken = AppDispatcher.register(@dispatchCallback)

  dispatchCallback: (payload) ->
    switch payload.eventName
      when 'new-address'
        # Add your new model accesible from payload.data
        # Backbone collections know how to post data

Step 6: Use your backbone store

Nice! You have a dispatcher and a store. All you need to now is make your form dispatch an event on submit.

Let’s get back to CreateEmailSpec.coffee and add some code to it.

it "should dispatch event on submit", ->
  spy = sandbox.spy(AppDispatcher, 'dispatch')
  renderedDOM = ReactDOM.findDOMNode(@component)

  React.addons.TestUtils.Simulate.submit(renderedDOM)

  expect(spy).toHaveBeenCalledOnce()
  spy.restore()

Once more, please. Run it and watch it fail. In order to make it pass our CreateEmail.js.jsx.coffee should look like this:

CreateEmail = React.createClass(
  submit: (e) ->
    AppDispatcher.dispatch
      eventName: 'new-address'
      data:
        email: @refs.email.getDOMNode().value

  render: ->
    `<div className="container">
      ...
      <form>
        <input type="text" ref="email" />
        <input type="submit" value="Create Forwarding Address" onClick={this.submit} />
      </form>
    </div>`
)

Views.CreateEmail = React.createFactory(CreateEmail)

Voila! We have a React view talking to a Backbone collection through a global dispatcher.

What’s next

For the sake of brevity and clarity I skipped form validation, view subscription to Backbone events and alike. But I hope this gives you a pretty good idea of how to merge Backbone, React, JSX and Coffescript together to make frontend development fun!

We are confident our renewed stack will help us to deliver enhanced user experience in the months ahead.

read more »