Sunday, August 21, 2016

It Should Have Just Worked

Out of the Dark

I was looking at my blog today and I realized I have been slacking off a bit when it comes to making updates.

So I am going to correct this.

First, What have I been doing?

Well, between working my regular day job, my two main side projects, family, and just life in general, there hasn't been much time for blogging.

With this post I intend to do the following:

  • Update my status on my side projects
  • Identify future topics
  • Document my latest "eureka" moment. (More of a "duh" moment really)

Pain Logger

Pain Logger is my main mobile app.

I have two versions on Apple's app store, a free version, with limited functionality, and a paid version.

Both apps were written in Objective-C and I have been extremely busy rewriting the paid version entirely in Swift.

If I had to choose to do this over, I would have advised myself not to rewrite the entire app.

But, here I am, and I am finally starting to see the light at the end of the tunnel, or the on-coming train, I'm not sure which.

I'm still struggling about what to do with the free version and how to or if I should merge the two code bases.

be

Be (we actually spell it with a lower case 'b', don't ask me why, that was the CEO's idea) is an application I have been working on with a small team for the past few months.

We are still in the prototype phase.

I am primarily responsible for the server side and the web client.

We are still a ways off from release, but things are moving forward and I have learned a lot from the project.

My latest effort on this project has been building an administrative portal and separating the web client from it's integration with Rails' sprockets.

Future Posts

With football (that is American Football for those outside the US) season rapidly approaching, to say I will be distracted is an understatement.

But I figure, I can do a lot of blogging while watching football.

Over the next few weeks I plan to talk about the following topics/experiences:

  • How I implemented theming in Pain Logger
  • The sync solution I used for Pain Logger
  • My experience in converting 'be' to a NodeJS build tool chain from Rails sprockets
  • The homegrown 'Flux' implementation I used for Pain Logger

My latest hurdle

Finally, I want to talk about one of those 'duh' moments I had recently.

You know the story, you find a problem, you look at your code, you say to yourself 'this couldn't possibly failing', yet it is.

So here goes.

One of the new features I am adding to Pain Logger is support for GeoFencing.

Yeah, if you are thinking to yourself this crazy idiot just said he was rewriting his app in Swift and now he is also adding new features at the same time, HAS HE LOST HIS MIND!!!!???

You would be right.

In fact this isn't the only new feature I am adding to Pain Logger.

Looking back now, and recognizing I still haven't got the update out, is a pretty good indicator this was A VERY BAD IDEA.

Anyway, I digress.

It was fairly simple to get Geofencing going, from a coding point of view but testing was something different.

When I first deployed it on my iPad everything was fine. It worked perfectly, but on my iPhone, it didn't work. What!?

I tried a TON of different things, including deleting and reinstalling the app, turning cellular data on and off, and changing any setting I thought that might possibly be affecting this on my phone.

But to no avail.

I can't even begin to enumerate the amount of logging I added to the app to see what was going on.

No matter what I tried, my iPad (wifi only) would work, even when I wasn't connected to a network, and my cell phone, which is always connected, would not.

So I began 'googling'.

Eventually, after spending a lot of time on Stack Overflow I took a different tact and said 'If I was a user having this problem, how would I search for an answer?"

I really thought I was headed to the "Genius" bar.

That line of thought led me to an Apple support post and the ultimate solution.

It turns out there was one more setting (shocking I know :-/) that I hadn't changed nor had I run across.

It is found under Settings->Privacy->Location Services->System Services.

You have turn on Location-Based Alerts.

One of the reasons this was so hard to find for me was that the "System Services" option is found at the bottom of the list of ALL of the apps you have installed.

One would have thought a standard option that is never removed would have been found first in the list, but nope.

Yeah, it makes sense now, and how this setting ever got turned off, I'll never know but another speed bump overcome, even if it was stupidity on my part.

Till next time.

Sunday, June 5, 2016

Devise Two-Step

DeviseTwoStep

Finally

Let me first say I am not a Devise expert by any stretch of the imagination. The project I am working on has a requirement to use two different models for authentication and I could not find a complete example of how to setup Devise to do this.

The documentation and several web sites and stack overflow articles I found gave hints on how to do it but I still had questions. So I thought I would write this post to show how I setup a test project to do it from end to end.

My goal is to have two models, user and admin that both are authenticated using Devise. Each model (I'll call it an account from here on out when referring to both) will have a set of pages that are only accessed when the account is logged in.

Additionally these protected pages are only accessible by one of the two accounts (depending on who is loved in). Finally, each account will have it's own (and separate) sign-in page and layout.

Much of the advice on the net recommended using a role based approach to solve this problem, but for many reasons that won't work for the app I will eventually apply this to. So a role based solution is off the table.

I started this investigation at the Devise website{***}. Unfortunately, I could not follow it enough to get a successful implementation. It felt like I was missing something.

The problem I kept running into was I would login as an Admin and when I logged out I would get redirected to the User's login page or if I logged in as the User I could then get to the Admin protected pages when it shouldn't. So something just wasn't clicking.

I next worked through this tutorial with the following deviations:

  • When I copied the devise views into the app I put them in their own directories with this command:
`rails generate devise:views User`
  • I did not do the section on Sending E-Mail and DelayedJob as they were not germane to the problem I was trying to solve

Once I had that going I created my Admin model and migrated my database.

rails generate devise Admin
rake db:migrate

Note: I did not add a name attribute to the Admin model like was done in the tutorial for the User model, as there was no need for it. I also left the registration support in so I could quickly add admin users, but obviously in a real app you wouldn't want to allow that.

I next created the Devise views for the Admin model (I had already copied the user ones when working through the tutorial):

rails generate devise:views Admin

This creates two directories under app/views, users and admins respectively. Under each directory will be sub directories for the different devise features that are supported.

Next I created sub directories in the controllers directory called users and admins and in those sub directories I created a controller for registration and session. This has to be done in order to customize registration and authentication for each of the models.

So for the User side I created a directory under controllers called ... wait for it ... users.

The registration controller (named registrations_controller.rb) looks like this:

class Users::RegistrationsController < Devise::RegistrationsController
  # disable default no_authentication action
  skip_before_action :require_no_authentication, only: [:new, :create, :cancel]
  
  protected

  def sign_up(resource_name, resource)
    # just overwrite the default one
    # to prevent auto sign in as the new sign up
  end
end

The session controller (named sessions_controller.rb) looks like this:

class Users::SessionsController < Devise::SessionsController
  # disable default no_authentication action
  skip_before_action :require_no_authentication, only: [:new, :create, :cancel]
end

Next is the registration controller for the Admin model (same name as above):

class Admins::RegistrationsController < Devise::RegistrationsController
  # disable default no_authentication action
  skip_before_action :require_no_authentication, only: [:new, :create, :cancel]
  
  protected

  def sign_up(resource_name, resource)
    # just overwrite the default one
    # to prevent auto sign in as the new sign up
  end
end

and the session controller for Admin (same name as above):

class Admins::SessionsController < Devise::SessionsController
  # disable default no_authentication action
  skip_before_action :require_no_authentication, only: [:new, :create, :cancel]
  # now we need admin to register new admin
  #prepend_before_action :authenticate_scope!, only: [:new, :create, :cancel]

  protected


  # def sign_up(resource_name, resoure)
  #   # just overwrite the default one
  #   # to prevent auto sign in as the new sign up
  # end
end

We are almost there I promise. Next are the changes to the routes.rb file:

Rails.application.routes.draw do
#  devise_for :admins
  devise_for :admins, module: 'admins', controllers: {sessions: 'admins/sessions', registrations:'admins/registrations'}
#  devise_for :users
  devise_for :users, module: 'users', controllers: {sessions: 'users/sessions', registrations:'users/registrations'}

  # These are the protected routes.
  # The pages controller is for the user model and the
  # admin_pages is for the admin model
  get '/secret', to: 'pages#secret', as: :secret
  get '/adminsecret', to: 'admin_pages#secret', as: :adminsecret
  get '/userhome', to: 'pages#index'
  get '/adminhome', to: 'admin_pages#index'

  # Define the root for when a user is authenticated
  authenticated :user do
    root 'pages#index', as: :authenticated_user_root
  end

  # define the root for when an admin is authenticated
  authenticated :admin do
    root 'admin_pages#index', as: :authenticated_admin_root
  end

  # default root (should never use this)
  root to: 'pages#index'
end

When you run the devise generator it will add a devise_for call in your routes. I have left those in (but commented out) to show what the default is so you can see how I adjusted the devise routes for the different models to point to their respective controllers.

Also you can see the "secret" pages and how they are defined as regular routes. I'll show them shortly. Finally I defined scoped routes for the "roots" for the different models.

Next is the application controller. This is where the "glue/magic" happens. I have included comments in the code so you can see what I was doing/thinking.

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  respond_to :html, :json

  # the layout should be specified by the resource (i.e. admin or user)
  layout :layout_by_resource

  protected

  # ensure name is allowed
  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) << :name  
    devise_parameter_sanitizer.for(:account_update) << :name
  end

  # if we are using a devise controller then we can check the
  # resource_name and return the appropriate layout, this can 
  # also be done at the controller level
  def layout_by_resource
    if devise_controller? && resource_name == :admin
      'adminlayout'
    elsif devise_controller? && resource_name == :user
      'userlayout'
    else
      'application'
    end
  end

  # Specify where to go after successful login again this is 
  # dictated by the resource that logged in
  def after_sign_in_path_for(resource)
    if devise_controller? && resource_name == :admin
      authenticated_admin_root_path
    elsif devise_controller? && resource_name == :user
      authenticated_user_root_path
    else
      root_path
    end
  end

  # Specify where to go after successful logout again this is 
  # dictated by the resource that logged in
  def after_sign_out_path_for(resource)
    if devise_controller? && resource_name == :admin
      new_admin_session_path
    elsif devise_controller? && resource_name == :user
      new_user_session_path
    else
      'application'
    end
  end

end

Next up is the protected content. For the user, he is directed to the pages index when properly authenticated. For the admin, she is directed to the admin_pages index when successfully authenticated. The controller for pages looks like this:

class PagesController < ApplicationController
  before_action :authenticate_user!

  layout 'userlayout'
end

By adding the before_action to the controller all routes will be forced to be authenticated.

The controller for the pages accessible to the admin look very similar:

class AdminPagesController < ApplicationController
  before_action :authenticate_admin!
  layout 'adminlayout'
end

Again all routes in this controller are protected by the before_action but this time the session must be a logged in admin.

With that said we are done. I modified the various views to indicate which one was being shown when you loaded it up. Check the completed code here here for what those views look like.

In summary, I guess I was just too dense to understand it but the key to all of this turned out to be how the application controller is configured.

Sunday, April 24, 2016

Editing Date in Rails MVC

Date_Select

I was working on a simple rails app to act as an administrative console for a larger project I am working on. The main application is a ReactJS based client so I haven't been doing much with Rails MVC, so my memory on using Rails' form helpers was a bit rusty.

I decided for the administrator's console, however I would use a standard Rails MVC design. Most everything came back quickly but one thing I had trouble with was how to edit dates using the Rails data_select tags. To get it to work end-to-end I had to piece several different pieces of information together.

So I thought I would write this short post to capture all that information in one place.

First, in the view for the form I configure the date_select like this:

<%= form_for goal, url:{action: 'goal_update'}, html: {class: 'form-horizontal'} do |f| %>
    <div class="form-group">
      <%= f.label(:start, 'Start:', class: 'col-sm-2 control-label') %>
      <div class="col-sm-10">
        <%= f.date_select(:start, class: 'form-control', disabled: disabled) %>
      </div>
    </div>
   <div class="form-group">
      <div class="col-sm-offset-2 col-sm-10">
        <%= f.submit('Save', class: 'btn btn-primary') %>
      </div>
    </div>
<% end %>

In this view code I have passed in a goal object and on line 1 I setup the form for it. Note: I am using Bootstrap here for most of the styling, with a little bit of my own CSS thrown in.

This goal has a start attribute which I setup the form element for on line 5.

The disabled attribute is passed into the view as well so I can use the same form code for when the administrator just wants to view the goal versus edit the goal.

Basically the view part of this is very simple and just requires following the syntax for the date_select tag.

It's a little more interesting we when get to the controller though.

Here is the relevant parts of goal_update from the controller. Note: goal_update is defined in my routes to point to a specific controller and action.

  def goal_update
    goal_id = params[:goal][:id].to_i
    @goal = Goal.where(id: goal_id).first
    ...

    @goal.start = date_from_params(params[:goal],'start')

    ... 
  end
  
  def date_from_params(hash, field_name)
    begin
      date_hash = %w(1 2 3).map { |e| hash["#{field_name}(#{e}i)"].to_i }
      return Date.civil(date_hash[0], date_hash[1], date_hash[2])
    rescue
      return nil
    end
  end

So you can see in line 2 all the information about the goal is passed in the params hash under the :goal key.

In line 2, I get the id of the goal to update and then load it up in line 3. Yes, I need more error checking here but thats not important for this post

Later in the method on line 6, I get the start date by calling a helper method I wrote to safely get the date from the params hash.

This helper method is shown starting at line 11.

Its important to note how the date values come in via the params object. The relevant portion of the goal hash will look like the following when it is submitted to the controller:

"start(1i)"=>"2016", "start(2i)"=>"4", "start(3i)"=>"27",

So the helper method takes the goal hash params[:goal] and the key for the date we want to construct 'start'. It uses the map function on line 13 to pull out the individual components and then on line 14 converts this to a Date which is returned. If anything goes wrong we catch any exceptions and return nil to indicate the date was not set.

And there you go.

One final note: It has been my intention to write a post once a week and as you can tell I haven't been able to keep that up over the last few months. I even thought I would just write a post once every two weeks, but that hasn't worked out very well either.

The problem is I need to balance project development with keeping this blog active. It's hard to do both. Right now project development is the higher priority, so for the foreseeable future I expect these posts to be a bit erratic. However, I am committed to keeping this blog active.

I do have some cool stuff I am doing in my currently active projects that I hope to write about in the near future.

So stay tuned.

Sunday, March 27, 2016

Avoiding Massive VCs

One of my biggest beefs with iOS development has been the lack of best practices particularly when dealing with what code belongs in the ViewController.

For my development, I like to design with these goals in mind:

  • Each class/method has one responsibility
  • Functions should not have side effects.
  • Well understood functionality should be abstracted away into their own classes.

When writing UIViewControllers, however, I find it tough to adhere to these principles. The reason, I think, is the fact that because the UIViewController essentially is the code for a view in your app it takes on many responsibilities, such as manipulating the view's widgets, holding state for the widgets, setting values on the widgets, and responding to actions taken on a widget.

I see examples of this type of design all over the Internet. This munging of the responsibilities leads to what has been commonly called the "Massive View Controller" design pattern.

There has been a lot written about how to avoid this pattern and why it is a bad thing, so this post may not be very interesting to those who are well versed in this anti-pattern.

For me, though, I have come to a point in my rewrite of my app, Pain Logger, that patterns are starting to emerge to mitigate this issue that I can use for future apps so I thought I would write these up as minimum for my own reference in the future.

If this has provides any value to you I would love to hear about it.

Avoiding Massive View Controllers

To avoid the Massive View Controller problem I have began using four patterns:

  • View Models
  • Unidirectional data flow
  • Services
  • Protocols Extensions

Note: For this discussion when I say "view" I mean the UIViewController as seen on a storyboard along with it's actual UIViewController class representation. My goal is to reduce the code in these view controllers as much as possible to meet the goals I strive for as outlined above.

View Models

The intent of a view model is to hold state for the view. That way when a particular value needs to be displayed on the view, the view asks it's view model for the data rather than storing the data in the view itself. This allows the view model to do two things:

  1. Hold the data in it's raw format
  2. Transform the data into exactly what the view needs to display.

A simple example would be a date. The view model can hold the raw NSDate object and when the corresponding view needs to display the date it can ask the view model for correctly formatted date (i.e. a string).

With this pattern, business logic (in this case formatting of a NSDate into a String) is moved out of the view code and into the view model.

I started my rewrite of Pain Logger thinking I would move all the data manipulation to a view model class for each view controller. In the end that's not exactly how it ended up, but for this discussion I'll keep it simple.

When a view controller first stands up it creates it's corresponding view model.

var viewModel = VC_ViewModel()

Then in the view controller I wire up the widget's action to the control. But the IBAction implementation only updates the view model and calls the method to refresh the UI.

Here is an example where I wired up a UISwitch:

    @IBAction func handleSwitchChanged() {
        viewModel.showGraph = showGraphSwitch.on
        refreshUI()
    }

The refreshUI() method just reads the values from the viewModel and updates the view's controls appropriately. In this case setting the showGraph attribute to true causes another widget in the view to be shown.

This pattern works well for moving the view's state out of the view controller class. But as I worked through this I ran into another pattern that makes it that much more powerful. This pattern is called 'Unidirectional Data Flow'

Unidirectional Data Flow

Unidirectional Data Flow comes from the 'Reactive' world. I first ran into this pattern with my web work using ReactJS. In this pattern a change is made to data via execution of 'actions'. These 'actions' update a central 'store' which then notifies it's listeners that the store was changed.

There are many implementations of this pattern. The one that seems to be getting a lot of traction is the ReSwift project.

One of the problems I ran into with using the 'View Model' pattern was initialization of the state. But when I incorporated that with UDF, things began to clean up a bit.

Now there is a 'global' store that represents the state of the system at any moment in time. The view models no longer hold state for the view, they are responsible for isolating the business logic for formatting the data from the store into the appropriate format for the view.

For example, in Pain Logger, when editing a pain area, a title must be displayed on the view. The view model exposes a computed attribute for the view's title like so:

    var title:String {
        let name = categoryState.categoryName
        if (name.length > 0) {
            return name
        }
        if let cat = category{
            if (cat.isNew()) {
                return "New Pain Area"
            }
        }
        return "Unknown"
    }

In this example categoryState represents the store, so now the view model doesn't hold state, only the store does. When the refreshUI() method is called on the view controller (after being told by the store that it changed) the view model defers to the "store" to get the value of the system state and then provides the view with the correctly transformed data value.

It should be noted that by adding UDF to the design most if not all of the attributes on the view model become computed values. View models now hold no state either. You can see that in the code above where category is used. category is actually another computed value that looks to the store to find the category that is being edited.

Another consequence that occurs by adding UDF is the view controllers now listen to the store for changes, and actions from the view are dispatched to the UDF system rather than calling the refreshUI method directly.

So for example the handleSwitchChanged() method from above becomes:

    @IBAction func handleSwitchChanged() {
        mainStore.dispatch(SetCategoryShowOnGraphAction(showOnGraph:showOnGraphSwitch.on))
    }

In this way most IBAction methods become one liners, very cool.

Services

The next pattern is a little more mainstream. Using this pattern I moved all async operations out to specialized "service" classes. Each "service" uses the singleton pattern (for all of those who don't like this pattern, I still find it useful for this case). Because of the introduction of UDF the service's don't hold state. They just update the stores.

I have services for local and remote data among other things. Since storing to a database should be done off the UI thread I call the correct service for what I want to do. It modifies the database appropriately and updates the store with the changed values after they have been successfully persisted.

Since for the most part these services work asynchronously I can offload the work that needs to be done, then the UDF system kicks in when the response is received.

Protocol Extensions

The final pattern, that I am just getting used to, is protocol extensions. To be honest I didn't fully understand the value of them until I did some more studying of the subject.

I thought that protocols were just like interfaces from Java, and that would be right, until you throw in extensions. That's when things change, A LOT!!

Call me dense or whatever, but it seems to me that only when you start using protocol extensions do you start to get LOTS of reuse.

So the key to this is to define a behavior you want a class to have say like the title property from above. Since the view models don't hold state either I can define a HasTitle protocol like so:

protocol HasTitle {
    var title:String {get}
}

extension HasTitle {
    var title:String {
        let name = categoryState.categoryName
        if (name.length > 0) {
            return name
        }
        if let cat = category{
            if (cat.isNew()) {
                return "New Pain Area"
            }
        }
        return "Unknown"
    }
    
    var category:PLCategory? {
        get {
            return categoryState.selectedCategory
        }
    }
    
    var categoryState:CategoryState {
        get {
            return mainStore.appState.categoryState
        }
    }
}

Now any class can conform to this protocol just by adding it to the class's definition. Because the extension is defined, as well, there is nothing for the class (in this case a view model) to define and it "just gets" the behavior.

This is extremely powerful and I am excited about adding this new found knowledge to my code base.

Conclusion

So there you have it. A brief overview of some of the patterns I have found useful in architecting an iOS app and to avoid the Massive View Controller problem.

Till next time.