Dan Rasband

Happy Wife App: Day 2

| Comments

Yesterday was the second day of development on the Happy Wife App concept. So far I’ve come up with a few designs, mostly for layout, and I’ve outlined the basic structure of the app.

Happy Wife App Layout

I’m not a great designer, but I love great design. I also love a challenge, so I’m going to try to design this first iteration myself. If people show interest in the app, I’ll get a real designer to help me out and create something truly awesome. For phase 1, though, I’m mostly going to try to make everything functional and user-friendly. Making things “pretty” is what’s hard for me.

How to Make My Wife Happy

| Comments

A couple of months ago I wanted to brainstorm some iPhone app ideas, so I grabbed a piece of blank paper from the printer and wrote at the top, “iPhone App Ideas”. I didn’t immediately have any great ideas come to mind, and it was late, so I decided to go to bed and have another go the next day.

When I got back to my desk several evenings later (I had completely forgotten about my brainstorming session), I found the paper had been filled out with several ideas. It looked like my handwriting, but I couldn’t remember ever writing any ideas down, and looking at the ideas, nothing rung a bell. Then I got to the third or fourth idea on the list: “How to Make my Wife Happy app”. It was then that I realized my wife had given me a few ideas to go from. :)

I dismissed the ideas quickly because my wife had written them to be funny, but more recently, the “How to Make my Wife Happy” app idea has been stuck in my head. I decided to plan out what it would be like if I actually built it out, and I think it is actually a great idea.

This is the description of the app that I wrote yesterday:

Description:

This app is meant to 1) educate husbands on what their wives want, 2) help them develop an emotional relationship with their wives, and 3) give them ideas of things to do for their wives to surprise them or otherwise make them happier.

Last night I decided that the app would have the following four main sections:

  • LEARN – where you can learn about your relationship with your wife, etc.
  • ACT – where you can find ideas to act on immediately to improve your relationship with your wife
  • TALK – where you can talk with other guys about marital problems (and solutions), get guy-to-guy therapy, and share ideas.
  • JOURNAL – where you can keep track of your progress and write notes about what you’ve learned

The app will integrate with Pocket, iCloud, Evernote, Calendar, and others to make it easy to learn and then put that knowledge to work and improve your relationship with your wife.

I’m going to build it. Is anyone interested?

Sacrificing for Family vs. Sacrificing Family for Family

| Comments

As I mentioned in my post about routine, my friend and I rented an office space in downtown Salt Lake City, so I’ve been coming here every workday morning to blog, think, and plan. At first, though, I was coming here after work and sometimes staying until 7:30 or 8pm. Jieun was okay with this because we decided it would be good for our future, and I committed to only doing it on Monday, Tuesday, and Wednesday. But after a couple of weeks of that, I couldn’t stand it anymore.

At first I thought Jieun and I were sacrificing for our family, by having me work in the evenings like that, and I thought it was better than me going home and working there, but it turned out that I was actually spending less time with my daughters than when I was freelancing from home. When I got home, it was already almost bedtime, but I wanted to spend more time with the girls, so they started to go to bed later and later and later. And yet it still didn’t feel like I was spending enough time with them.

That’s when I realized that I was sacrificing time with my family for my family, which doesn’t really make sense. It could make sense in the long term, but for us it didn’t. How much money I make isn’t going to affect my children as much as how much time I spend with them — especially when they’re young.

That’s why about three weeks ago I decided to switch things up and come here early in the morning. I still miss being able to see them wake up in the morning, and being able to get them cereal or rice with seaweed, but I’m now sacrificing more of my own time so that I can be with my family.

Sacrifice, in one definition, is giving up something good for something that’s better. When I was spending my evenings working I was sacrificing something awesome for something quite mediocre, and now I’m sacrificing something pretty mediocre (mostly extra sleep) for something pretty awesome, and it feels great.

L10n Best Practices in Rails

| Comments

We’ve been doing Ruby on Rails projects here at Agency Fusion for a year now. I’m somewhat of a stickler for doing things The Right Way™. Luckily, the Rails framework has a pretty nice method for translating strings throughout the site. In this post I’m going to outline some of the different ways that you can implement localized strings and the advantages and disadvantages of each.

First, in Rails there are two methods used for localization: translate (aliased t) and localize (aliased l). Pretty straightforward, right? See the ActionView::Helpers::TranslationHelper docs for more info. Here are some quick examples of them being used in the wild:

app/views/example/index.html.slim
1
2
3
4
5
# In slim
h1 =t 'This is the header!'

# Localized date (slim only)
span.date =l @user.created_at
app/views/example/index.html.erb
1
2
# In erb
<h1><%=t 'This is the header!' %></h1>

I like to put the t next to the = because it looks nice and concise, but the following is the exact same thing:

app/views/example/index.html.slim/erb
1
2
3
4
5
6
7
# In slim
h1 = t('This is the header!')
# In erb
<h1><%= t('This is the header!') %></h1>

# Localized date
span.date = l(@user.created_at)

The yaml file with translated strings would look like this:

config/ko.yml The Korean translation.
1
2
ko:
  "This is the header!": "이것은 헤더입니다!"

Okay, now let’s discuss the above strategy.

I18n gettext style

The above type of translation is a lot like the gettext style of translating strings. You provide the full English translation, and that translation is used as a sort of key. The problem with doing it this way in Rails, though, is that Rails doesn’t have a full implementation of gettext, so it doesn’t allow you to attach a domain and/or context to a string. What this means is that all instances of 'This is the header!' will be translated exactly the same across all uses, even if it makes sense to translate one instance a different way for some languages. To sum up:

  • Advantages:
    • Easy and straightforward.
    • If there are no translations for that key in the appropriate language, it will just use the key, which is great for English.
  • Disadvantages:
    • There is no way to contextualize the translation.

Symbolized Keys

Another method that has similar strengths and weaknesses is to you use symbols as translation keys:

app/views/example/index.html.slim
1
h1 =t :this_is_the_header
config/ko.yml
1
2
ko:
  this_is_the_header: "이것은 헤더입니다!"

This is nice, mostly because symbols are such a beautiful feature of Ruby syntax. They have the same advantages and disadvantages of using a full-text key, except that when there isn’t a translation available in the yaml file, it will return a capitalized version of the string:

This Is The Header

This is okay in a lot of instances, but again, it doesn’t provide the contextualization that you often need with translations.

A contextualization pattern for Rails i18n

To include context, you can namespace your keys. This is a little bit of a combination between the first two approaches with a little twist:

app/views/example/index.html.slim
1
h1 =t '.this_is_the_header'

The reason I gave the full relative path to the view was so that we could see what controller and action the view belonged to. The above example would be the view for the ExampleController’s index action. This is important because the . before this_is_the_header in the translation key automagically provides controller/action context to the key. The yaml file then looks like this:

config/ko.yml
1
2
3
4
ko:
  example:
    index:
      this_is_the_header: "이것은 헤더입니다."

I love this way of doing things, but it is also not without disadvantages. The main disadvantage is that you have to now have a translation of the same basic key (this_is_the_header) for every view that uses it. This can suck for some strings that you use throughout the site.

One method to overcome this, though, is to use the :default option as an option argument to the t method:

app/views/example/index.html.slim
1
h1 =t '.this_is_the_header', default: t('common.this_is_the_header')
config/ko.yml
1
2
3
ko:
  common:
    this_is_the_header: "이것은 헤더입니다!"

Now the key has a default translation, but can be overridden per context if needed. So if there is another view that you decide to override for Korean, you can do so without affecting all other instances of the translated key:

app/views/example/other.html.slim
1
h1 =t '.this_is_the_header', default: t('common.this_is_the_header')
config/en.yaml
1
2
3
en:
  common:
    this_is_the_header: "This is the header!"
config/ko.yaml
1
2
3
4
5
ko:
  common:
    this_is_the_header: "이것은 헤더입니다!"
  example:
    other: "이게 헤더잖아!"

The Korean translation above defaults in all instances except the other action to the common.this_is_the_header translation, but the English is the same across the board.

This method, unfortunately still has one ugly disadvantage, and that is that translating strings can sometimes make for really long lines in your views when you provide interpolated elements to your translations:

config/ko.yml
1
2
3
ko:
  common:
    this_is_the_header: "%{name}, 이것은 헤더입니다!"
app/views/example/index.html.slim
1
2
h1 =t '.this_is_the_header', name: @user.name, \
  default: t('common.this_is_the_header', name: @user.name)

Maybe there’s a better way to deal with this, but I am as yet unaware of what it might be. Leave any ideas in the comments, thanks!

Kids Are Entropy

| Comments

I realized yesterday that kids (at least my kids) are the personification of entropy. We cleaned our carpets on Saturday with my parents’ carpet cleaner, and before we were done our kids had spilled water, cereal, and strawberry juices on the floor. They also decided to take out all of the toys and spread them all over the floor.

It’s not like this is a novel occurrence; it happens all the time. Every day, in fact. But it just struck me as funny yesterday. It’s not so funny to my wife, though.

The Pursuit of Unique Knowledge

| Comments

When I started getting serious about wanting to write a blog a few months ago, I often felt paralyzed. I felt that I needed to be the one source for knowledge on some particular topic and then, only then, could I write a blog that was worthwhile. And maybe that’s still true; there are so many blog articles out there already about Ruby and Rails and C and other stuff that it is difficult to break through and come up with unique content.

When I realized I was not allowing myself to write a blog because of this feeling, I started thinking about what knowledge I had that nobody else in the world had, or at least that nobody else in the world was writing about.

And I came up with nothing.

But that’s not the point of this post. The point of this post is to contemplate the idea of unique knowledge: its existence, how to obtain it, and whether its worth it in the end anyway.

Is there really such a thing as unique knowledge?

One of the first questions that came to mind while thinking about what I could write was “Is there really such a thing as unique knowledge.” I quickly came to the (now obvious) conclusion that, yes, there is such a thing as unique knowledge. Unique knowledge comes from 1) unique experiences, 2) intense research into previously unresearched territory, and 3) innovation – building and creating new things.

The human experience is interesting, though, and while we have unique experiences and therefore have unique knowledge, much of human experience is not unique in terms of category or emotion. Most everyone experiences happiness (I hope), sadness, heartache, loss, excitement, arousal, stress, and exhaustion, among a whole lot of other emotions. A lot of people write stories and film movies and create art to express and more deeply understand these emotions.

Another thing that’s interesting about the human experience is that we as humans love to share our experiences with others. Even I, an introvert, enjoy telling my coworkers, my wife, my brother, whoever really, about my life experiences. Unique knowledge that comes through experience is often disseminated rapidly and soon becomes widely shared knowledge.

How to go about getting unique knowledge

When researchers look at human experience, though, they often come up with new knowledge about why we experience things the way we do, or how certain experiences affect our lives. Because the number of variables involved in experiences is so huge, there will probably always be room for doing more research in that area, and unique knowledge will be generated, then disseminated to other researchers or to the public.

It’s difficult to get to the point, though, where you are able to understand a topic well enough to know what about it is yet unknown. From my inexperienced perspective, it seems to me that half the battle when trying to get a Ph.D. is figuring out what 1) interests you and 2) hasn’t been researched yet. The other half is convincing other people that your research is worth doing and then actually doing the research, of course. Anyone with a Ph.D., please set me straight if I’m off here.

Basically, what I’m getting at is illustrated by Matt Might in The illustrated guide to a Ph.D.. Anything outside of that circle is novel knowledge.

The last way of getting unique knowledge (that I can think of this morning), is to innovate by building and creating new things. There are infinite possibilities here. The Arduino platform, for example, was not unique in some ways, but its particular schematic, its use of components, and its combination with a software program built specifically for it was unique, and that enabled it to really take off.

Is unique knowledge worth anything, and/or is its pursuit worth it?

Unique knowledge in and of itself is worth squat. It’s kind of like the philosophical discussions on reality where reality only exists with perception. So if you’re the only one with knowledge about something, you might as well say that that knowledge doesn’t exist at all. Once knowledge is shared with others, used to create something new, or otherwise utilized to some effect, that is when it becomes valuable. Whether that value is good or bad is another discussion altogether.

Conclusion

My frustration for not having unique knowledge about anything was definitely misguided. First of all, having unique knowledge is of no worth to anyone unless I share it (and then my unique knowledge bank account is depleted). Secondly, it can take a lot of work to obtain unique knowledge, so it’s okay if I’m not quite there yet. And lastly, I’m pretty sure everyone has some knowledge that, while not unique, is not well-known, and sharing that knowledge in a blog might just be worth it to someone.

It’s now my task and my desire to go out and experience new things, start researching something that I’m passionate about, create things as often as possible, and then share what I learn in the process.

I’m glad I got that out there. :) Thanks for listening.

Handling Transactions in Rails

| Comments

I’ve had a few opportunities lately to work with transactions in Rails. Transactions are useful when you have more than one model that needs to be saved in one pass, but you don’t want to have to deal with deleting one if the other doesn’t save successfully, etc. Basically, if you save a model within a transaction and it fails, any other models that were saved in that transaction will be rolled back.

Here’s a quick example:

posts_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class PostsController < ApplicationController
  def create
    @post = Post.new(post_params)
    @tag = Tag.new(tag_params)

    Post.transaction do
      @post = Post.create!(post_params)
      @tag = Tag.create!(tag_params)
    end
  end

private
  def post_params
    params.require(:post).permits(:title, :body)
  end

  def tag_params
    params.require(:tag).permits(:name)
  end
end

So, if either @post.save! or @tag.save! fails, the entire transaction will be rolled back. Notice that I’m using save! and not save. This is because you have to throw an exception for the transaction block to realize the the transaction has failed. The problem with this, though, is that the transaction doesn’t automatically rescue the error. You have to do that yourself. I’ll leave that as an exercise for the reader. Just kidding! Check this out:

posts_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# ...
  respond_to :html

  def create
    @post = Post.new(post_params)
    @tag = Tag.new(tag_params)

    begin
      Post.transaction do
        @post.save!
        @tag.save!
      end
    rescue => e
    end

    respond_with @post
  end
# ...

Note: check out this best practice for an explanation of the rescue syntax: Don’t rescue Exception, rescue StandardError

Notice anything wrong? I didn’t at first, but what you may not notice is that if the post is created successfully, but the tag is not, the following quirkiness ensues: the post is rolled back, but the instance retains the id=1 attribute. This causes the respond_with @post to fail because there isn’t a Post with id=1 — it got rolled back! So what do we do to compensate?

I don’t know the best way to deal with this, so if you have better ideas, please leave them in the comments and I’ll update this post. Having said that, here’s an idea that works:

posts_controller.rb - Re-instantiate @post in rescue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# ...
  def create
    @post = Post.new(post_params)
    @tag = Tag.new(tag_params)

    begin
      Post.transaction do
        @post.save!
        @tag.save!
      end
    rescue => e
      @post = Post.new(post_params)
      @post.valid?
      render :new
      return
    end

    respond_with @post
  end
# ...

Running @post.valid? on the newly instantiated object will build all of the model’s errors for display on the form, but it will no longer have the id that was messing things up before.

I’m not sure if I have to use render :new because I’m using Rails 4.0 or if respond_with always renders :index when the creation fails. I’ll do some more research and update the post later.

Error Handling in Rails Controllers

| Comments

Yesterday I said that I was going to start writing blog posts about real-world programming problems and their solutions. The first one I’d like to start with is error handling in Rails controllers.

There are many ways to deal with errors and many errors that might need to be dealt with in Rails controllers. Let’s first take the example of the create action for a standard CRUD controller:

posts_controller.rb
1
2
3
4
5
6
7
class PostsController < ApplicationController
  def create
    @post = Post.new
    @post.update_attributes(params[:post])
    redirect_to :index
  end
end

There are a few problems, though with the code above. For one, it doesn’t check the parameters at all, so if there are any parameters listed in the params hash, it will throw a ActiveModel::MassAssignmentSecurity::Error exception. Obviously, this is no good. We can fix that by using the strong_parameters gem:

Gemfile (part of Rails 4.0 core, but not 3.x)
1
gem 'strong_parameters'

We’ll also want to check to make sure the update_attributes method returns true.

posts_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class PostsController < ApplicationController
  def create
    @post = Post.new
    if @post.update_attributes(post_params)
      flash[:notice] = t('posts.create.success')
    else
      flash[:error] = t('posts.create.error')
    end
    redirect_to :index
  end

private
  def post_params
    params.require(:post).permit(:body, :title, :tags)
  end
end

That’s better. The biggest problem now, though is that when we redirect to the index action, we lose all the model errors that we could otherwise be displaying on the form used to create the post. Here’s one way to handle that:

posts_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# ...

  respond_to :html # You need this to be able to use respond_with

# ...

  def create
    @post = Post.new
    if @post.update_attributes(post_params)
      flash[:notice] = t('posts.create.success')
    else
      flash[:error] = t('posts.create.error')
    end
    respond_with @post
  end
# ...

Now, by using the magical respond_with (see Plataformatec’s article about respond_with, Embracing REST with mind, body and soul) we can automatically render the new or show action, depending on whether the post was successfully updated or not.

I hope you’re wondering why I’m using @post = Post.new and then @post.update_attributes instead of just Post.create or @post = Post.new(post_params) and then @post.save. The main reason I’ve used that paradigm here is because, in the real world, I like to use the CanCan gem, which allows me to use the load_and_authorize_resource method at the top of my controller. This in turn automagically creates my @post instance variable so that I don’t have to instantiate it myself:

posts_controller.rb with cancan
1
2
3
4
5
6
7
8
9
10
class PostsController < ApplicationController
  load_and_authorize_resource
  # ...
  def create
    # @post is already made available by cancan, so no need to create it
    if @post.update_attributes(post_params)
    # ...
  end
  # ...
end

Because of this, create and new become useless and using update_attributes becomes, IMHO, the cleanest alternative.

Leave me any comments if you have questions or if you think there’s a better way. Thanks!

Update 2013-08-01: In Rails 4.0, if you use the scaffold generator, a lot of this stuff is already handled for you, including the param handling and some minimal error checking.

Next Up: Handling transactions in Rails

Real World Programming Tutorials

| Comments

If you’re at all like me, you spend a good amount of time almost every day learning new programming languages or brushing up on programming languages and technologies you already know. If there’s one thing that I hate about most tutorials is that they skip the real world problems. I understand that tutorials are trying to get the basics across, so they don’t want to muddy your mind up with extra stuff, but that means that there are no good tutorials with information on how to solve the real world stuff, like error handling or catching exceptions or making sure your code is secure.

Basically what I hate is the sentence “this is left as an exercise for the reader”.

I think the problem in the past was probably related to getting books published. When you edit a book, you have to get rid of stuff that isn’t useful to its core purpose. But with online books and tutorials, you can have collapsible content, footnotes, links, etc. I think it’s time to take advantage of those and beef up the programming tutorials that are out there.

Over the next few days, I’m going to write some tutorials on real world programming problems that I know decent solutions to. A lot of these solutions I’ve had to come up with on my own, so I don’t really know if they are the best solution or not, but they work.

Update: I will be linking to the articles here as I write them:

  1. Error Handling in Rails Controllers

The Power of Routine

| Comments

I have been discovering the power of routine lately. My friend and I rented a small office space on the outskirts of downtown Salt Lake. The building it’s in is quite interesting. It was built at least 30 years ago, and it’s age shows, but the current owners have great plans and have been slowly renovating it.

When my wife Jieun and I first discussed renting this space, we were concerned about how much time I would spend here instead of with my kids and her, so we decided I would come here on Monday, Tuesday, and Wednesday evenings, and then the rest of the week would be spent with the family. That worked, kind of. I still felt like I wasn’t getting enough family time, the kids were going to bed later and later, and Jieun was often asking me to come home early because she’s pregnant and has morning (actually late-afternoon) sickness.

So I decided I would come in to the office in the mornings, and that I would come in every weekday instead of just Monday, Tuesday, Wednesday. So for the last two weeks, I’ve been consistently waking up earlier and getting to the office between 7 and 7:45 every morning. This new routine has helped me restart my blog (after 2 years of it being a maintenance page), it’s helped me find time to re-evaluate my career and also decide what side projects I’m going to work on, and I just feel more productive and happier.

My kids, too, thrive when we stick to routine. In our home I usually get the privilege of putting our kids to bed at night. We head upstairs (often with some resistance) to get into the tub. After my girls are all washed up, they get dressed and put on some lotion, then brush their teeth. Then we read a couple of bedtime stories, say our prayers, and then listen to a couple of children’s hymns. If we follow this routine, I’m usually able to step out and let them fall asleep on their own, but when we don’t follow the routine, it’s a nightmare trying to get them to settle down.

A friend of mine (Christy Namee Eriksen) has been doing something that, in my opinion, is pretty remarkable. Every single day she tries to create something, whether it’s a drawing, a crafting project, or a new website. Then she takes a picture and uploads that to instagram and her blog and such. So far she’s done something every single day for almost seven full months. I haven’t talked to her about how she feels things are going, but I can tell that she enjoys creating new things and I know she has some pretty amazing projects in the works that may have never happened if she hadn’t started her #createdaily routine.

While routines can be powerful in bringing about good, they can also be very degrading and can slowly rot you to the core. Imagine the routine of taking a smoke break every few hours every day, or the routine of watching reality TV every night, or the routine of going to the bar every night. Consistently eating junk food or indulging in other physical pleasures will make you lazy, eat at your will power, and even cause physical or mental illness.

I’m not saying that eating a bag of salty, greasy potato chips while watching your favorite TV show every once in a while is going to kill you, or even that that’s necessarily bad. It’s just become apparent to me that I need to be more aware of my routines, and consciously, actively work to create good routines. Doing so is increasing my will power, bringing order to my life, and helping me be happier over all.