Friday, May 4, 2012

Java PageCheck

I've been doing some Java programming on my own. I am working on smaller programs to get back in the groove. Made a Factorial program and an assignment I found called FizzBuzz as well as other small programs.

I wanted to do something more but didn't know what to do or where to start. So, I decided to go back to the beginning and redo one of my first programming assignments, PageCheck. PageCheck is a program that takes an URL and a time interval and returns true if the corresponding page has been modified within the time interval, and false otherwise. This is the basic version.

The program below seems to be correct. For some webpages, it returns the correct vales. For other webpages, the values are not correct. These webpages don't seem to have a last modified date. There last modified date is 'Wed Dec 31 14:00:00 HST 1969.' These are webpages like Amazon, YouTube, and ics.hawaii.edu. getLastModified() Returns the value of the last-modified header field. The result is the number of milliseconds since January 1, 1970 GMT. The 1969 date is making last modified return 0.

I DON'T GET IT?


1:  import java.io.IOException; 
2:  import java.net.URL; 
3:  import java.net.URLConnection; 
4:  import java.util.Calendar; 
5:  import java.util.Date; 
6:   
7:   
8:  /** 
9:   * The CheckPage class implements a system to notify the user  
10:   * when a webpage has been modified within the past 24 hours. 
11:   *  
12:   * @author Keola Ng 
13:   * @version $Id$ 
14:   */ 
15:  public class CheckPage { 
16:    
17:   /** The url connection object that connects to the web page to check. */ 
18:   private URLConnection urlConnection; 
19:    
20:   /** The time interval to check the web page. */ 
21:   private int timeInterval; 
22:   
23:   /** 
24:    * Constructs a valid PageCheck object otherwise throws an exception. 
25:    *  
26:    * @param urlString The url of the web page to check. 
27:    * @param timeInterval The time interval to check the web page. 
28:    * @throws IOException problem connecting to the url in urlString. 
29:    */ 
30:   public CheckPage(String urlString, int timeInterval) throws IOException { 
31:    URL openUrl = new URL(urlString); 
32:    this.urlConnection = openUrl.openConnection(); 
33:    this.urlConnection.connect(); 
34:    this.timeInterval = timeInterval; 
35:   } 
36:    
37:   /** 
38:    * Determines when the web page was last modified. 
39:    *  
40:    * @return The long value of last modified date. 
41:    */ 
42:   public long getLastModified() { 
43:    return this.urlConnection.getLastModified(); 
44:   } 
45:    
46:   /** 
47:    * Checks if the URL has been modified within a specified time. 
48:    *  
49:    * @return URL has been modified before or after the timeInterval. 
50:    */ 
51:   public boolean isModified() { 
52:    Calendar currentCalendar = Calendar.getInstance(); 
53:    int intervalUnit = 3600000; 
54:    int lastModified = (int) (getLastModified() / intervalUnit); 
55:    int currentTime = (int) (currentCalendar.getTimeInMillis() / intervalUnit); 
56:     
57:    int num = currentTime - lastModified; 
58:    System.out.println("Date: " + new Date(currentCalendar.getTimeInMillis())); 
59:    System.out.println("Last modified: " + new Date(getLastModified())); 
60:    System.out.println(getLastModified() + " / " + intervalUnit  
61:                + " = " + lastModified); 
62:    System.out.println(currentCalendar.getTimeInMillis() + " / "  
63:                + intervalUnit + " = " + currentTime); 
64:    System.out.println(currentTime + " - " + lastModified + " = "  
65:                + num + " < " + this.timeInterval); 
66:     
67:    return ((currentTime - lastModified) < this.timeInterval); 
68:   } 
69:   
70:   /** 
71:    *  
72:    * @param args 
73:    * @throws IOException  
74:    */ 
75:   public static void main(String[] args) throws IOException { 
76:     
77:    CheckPage cp = new CheckPage("http://www.ics.hawaii.edu/", 24); 
78:    if (cp.isModified()) { 
79:     System.out.println("True"); 
80:    } else { 
81:     System.out.println("False"); 
82:    } 
83:   } 
84:  } 

Thursday, October 27, 2011

Blog Purpose

My blogging has been erratic and without purpose. There has been no reason behind any of the blog posts I've written. I want there to be a purpose and a future goal for my blogging. I've decided to work on my online presence. My goal is to create a professional persona to help me asses my strength and weaknesses of my programming capabilities.

The purpose of my blog is to showcase my learning. I will start detailing everything I'm working on.
  • Demonstrate my willingness and curiosity to continue increasing my programming knowledge.
  • Demonstrate I understand content related to programming.
  • Demonstrate my researching ability.
  • Demonstrate my writing ability.
  • Demonstrate my critical thinking ability.
  • Demonstrate my creativity.
  • Through my writing, develop and demonstrate my unique professional personality and character.
  • Develop and demonstrate my social media skills.
  • Begin developing my professional brand, not as a job-seeker in my field, but as a thought leader in my field.

My writing to this point has not clearly demonstrated any of these standards. One of my goals is to be able to clearly articulate in my writing what I'm working on so that everyone can understand. When I write what I'm working on, I want the newbie to the professional to understand what I'm explaining. I always hacking on something, whether it's Java or Rails or CSS and XHTML, I will have something to write about. It will take a lot of deliberate practice to get my writing to this point.

Wednesday, October 26, 2011

Apache Ivy

In researching Apache Ant and how to create a build.xml file, I discovered Apache Ivy. Apache Ivy is a dependency manager that can easily be integrated with Apache Ant.

The main and most frequent way to use ivy is from an ant build file. However, ivy can also be called as a standalone application. If you use ant version 1.6.0 or superior, you just have to add ivy namespace to your project (xmlns:ivy="antlib:org.apache.ivy.ant") attribute of your project tag, and you can call ivy tasks.
 <project name="sample" default="compile" xmlns:ivy="antlib:org.apache.ivy.ant"> 
The build will use Apache Ivy to download, install, and manage third party libraries of the different tools needed for the project. The retrieve task copies resolved dependencies anywhere you want in your file system. Below is an example of adding checkstyle to the project.
1:  <target name="install-checkstyle" description="Install checkstyle."> 
2: <ivy:retrieve module="checkstyle" organisation="com.puppycrawl" revision="5.4" pattern="${basedir}/lib/checkstyle/[artifact].[ext]" sync="true" conf="bundled" type="jar,report"/>
3: </target>

Tuesday, October 18, 2011

Build System

The build system is extremely important. It provides a standardized way for anyone to build the system. Users can build and test the system without an IDE. Developers can build and test the system using their IDE of choice. This automated build is helpful in preventing errors, testing, and deployment. Developing a robust build system can ease the process when maintaining a large and/or complex software system.

My build system will need to become a template. As a template, I can adapt it to any project I create. The build system will be modular and extensible to become as big or as small as needed. It will integrate any third party build tools. It will handle junit, checkstyle, and any other third party build tools that the build system requires. It will be able to download, install, and manage all third party libraries needed. It will support web application development.

Below is the beginnings of a build file. It contains two targets, clean and compile. It's very simple in what its doing. I am studying the Ant manual to learn how to integrate the third party build tools and libraries into the build system.

1:  <project default="default">
2: <description>
3: The build file.
4: $Id$
5: </description>
6:
7:
8: <property name="src.dir" location="${basedir}/src"/>
9: <property name="build.dir" location="${basedir}/build"/>
10:
11:
12: <target name="clean"
13: description="Delete build/ directory.">
14: <delete dir="${build.dir}"/>
15: </target>
16:
17: <target name="compile"
18: description="Compiles the code.">
19: <!-- Ensure that the build output dir exists. -->
20: <mkdir dir="${build.dir}/classes"/>
21: <!-- Now compile the system. -->
22: <javac srcdir="${src.dir}"
23: destdir="${build.dir}/classes">
24: </javac>
25: </target>
26: </project>

Thursday, October 13, 2011

Configuring My Java Build Environment

In my efforts to improve my programming skills, I have decided to get back into Java programming and building large projects. My previous involvement with a large Java project was seven years ago as a university of Hawaii student with the CLEW system. The Collaborative Educational Website (CLEW) was a web application development framework for collegiate department websites.

Environment Configuration

The current laptop I will be working on is a Toshiba Satellite A505 running on Windows 7 64-bit. It has a 1.60 GHz processor, 4 GB RAM, and over 100 GB of free space. My first step is to create a high quality Java software development environment. I downloaded and installed the Java 7 JDK and JavaDoc documentation. I added %java%/bin to my computers PATH variable. I downloaded and installed the Eclipse 3.6.2 IDE. I chose "Eclipse IDE for Java EE Developers" to work on the Java projects. To improve the performance of Eclipse, I modified some runtime options. Increase the heap space for Eclipse. I have at least 2GB RAM. In the eclipse.ini file, I changed -Xms=40m to -Xms=512m and -Xmx=512m to -Xmx=1024m.

To verify my configuration was working, I wrote a couple of basic programs in my eclipse IDE. I wrote the generic HelloWorld program that worked fine. I wanted to try something else so I searched online and found a simple program to implement called FizzBuzz. FizzBuzz is a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". I was able to implement a working FizzBuzz program. My initial configuration was working.

Build System

This is the point in my configuration where I am stuck. The build system I used for CLEW included apache ant, jakarta tomcat, junit, checkstyle, and other tools. Are these tools still relevant?

In my research for build tools, the top two I came across were Ant and Maven. Ant is open source, Java-based, extensible, and uses XML configuration files. Maven is project management technology that uses convention over configuration. Ant is still very popular and I am familiar with the Ant concepts. Every project requires an Ant build file, build.xml. Each build file is composed of targets. Each target is composed of tasks. And targets can have dependencies.

I downloaded and installed Apache Ant 1.8.1. I added %ant%/bin to my computers PATH variable.

Now What?

Next in configuring my Java build environment will be to include the different tools to help build a working project. I will look into junit, checkstyle, and other tools currently being adopted. When I get a build environment up and running, I will begin my Java programming.

Thursday, January 13, 2011

Learning by Doing

After graduating from the University of Hawaii, I fell into a programming funk. I didn't know what to do, how to get started, or where to get help. I felt like none of the courses I took prepared me to take a project from development through to distribution. I missed not having access to Professors, TA's, classmates, and friends. I finally took action and contacted my mentor for guidance.

His advice was to just start hacking. Do anything. Think of an idea and try to implement the program. Work by trial and error. If you encounter an error, try to figure it out with research and fix the problem. There is no better way to learn then to just do it.

I found the following on a website the echoes this sentiment.
Program. The best kind of learning is learning by doing. To put it more technically, "the maximal level of performance for individuals in a given domain is not attained automatically as a function of extended experience, but the level of performance can be increased even by highly experienced individuals as a result of deliberate efforts to improve." (p. 366) and "the most effective learning requires a well-defined task with an appropriate difficultly level for the particular individual, informative feedback, and opportunities for repetition and correction of errors." (p. 20-21) The book Cognition in Practice: Mind, Mathematics, and Culture in Everyday Life is an interesting reference for this viewpoint.
This concept of learning by doing would have been nice to have done while at UH. Looking back I feel my focus was more on completing assignments before the due date to get the best grade to pass the class to get to graduation. I didn't immerse myself into the subject to fully understand it and relate it to a real world problem. Because of this, I didn't have the right mindset or ask the right questions. I would've liked to learn by doing with the class, during class, with the professor giving feedback and correcting errors as he instructs. My ideal situation would've allowed more natural learning and less lecturing.

I've been thinking a lot about my student self. I feel I approached learning all wrong. I put more effort into getting through my courses then being in the moment and participating. I've come to realize my goals were geared towards doing what I needed to do to move up instead of understanding the material. It would've been amazing to be given a difficult task and allowed to fail without the consequence. My failure would have been an opportunity to teach me where I went wrong and how to correct the mistake for next time instead of failing me with no idea or explanation why my work was unsatisfactory and forced to retake the course.

It wasn't all bad. I had a few courses that allowed me to learn by doing. We worked on real world projects. I was able to receive informative feedback and correction on errors. In one of these classes I was introduced to pair-programming. Pair-programming is a great concept.

Over the past year of I've been learning a new programming language and hacking away implementing a variety of programs. I am gaining a deeper knowledge of Ruby on Rails, CSS, and XHTML. In this process I'm learning more about utilizing the MySQL database, how the MVC paradigm works, how to work with plugins and gems, authentication, uploading images and videos, dynamic select menus, and many more things. I am coming to the conclusion that a year of learning by doing has given me a better understanding then the majority of Computer Science courses I took at UH. Out of the 15 or more ICS courses I took during my time at UH, only two were helpful, ICS 413 and ICS 414.

I will be continuing my learning by doing. My current project is a web application using Rails. My ultimate goal is to get my webapp online. I also plan on getting back into Java development. My last foray with Java was using the Struts web application framework, eclipse, ant, tomcat, mysql, and cvs. I will be looking into what I need to develop with Java and if any of the preceding tools are still relevant.

Thursday, December 16, 2010

Whatcha Been Doin? A Conversation

It's the holiday season and we are visiting with family and friends. We are out gathering with people at parties or games or whatever. While hanging out with everyone we talk to each other.

One of the early questions asked to begin a conversation is "what you been up to lately" or "what do you do." I've participated in and listened to some conversations that began this way. Over the past month I have engaged in a dozen or so conversations and listened to a bunch more that began this way. I will note that I am not the best conversationalist.

When family, friends, or strangers came up to me and ask me that question, I fill them in on the hacking and trading I've been doing. I get two responses to my answer, "that's great" and they walk away or "that's great" and they change the subject. I did not get one person to pursue further into what I'm doing or exhibit any interest in what I've said. I've come to the conclusion that it could be one of two things, 1) hacking and trading are not interesting for the people I talked with or 2) my delivery in explaining what I'm doing was not clear and understandable for anyone to continue with that conversation topic. I believe the problem is with the latter.

In listening to other similar conversations, the response was much different. The questioner was engaged with the answers and continued with follow up questions to gain a deeper knowledge of the subject. I too became fascinated with what people are doing.

So, I've been trying to figure out why my delivery failed. As I noted earlier, I am not the best conversationalist. I don't participate in many conversations because I have a weak and soft voice and many people have a difficult time hearing me, especially in loud areas. I wing it every time I tell people what I'm doing so its probably not succinct and a little confusing. I need to practice.

I'm looking to improve in this area. In my research I've come across the concept of Branding. I will be working on Brand Me. I want to be able to articulate what I'm doing better. Maybe then I will get people interested in learning more.

Monday, October 4, 2010

The Past Couple of Weeks

My mom came up to me and said, "do you realize for the past couple of weeks you've been on the computer from the moment you get up until the time you go to bed." I did not realize that. I've been so focused on what I've been doing, time has flown by. I am enjoying the work I am putting my time and effort into. All I've been doing is trading and hacking. I want to get better in these two disciplines.

I spend time on my trading looking at charts for patterns, support and resistance levels, and direction. I look back at my previous trades to check if I'm following my trading rules. I do research for my trading journal project.

I spend time on my hacking working on my project. I'm teaching myself Ruby on Rails. My Rails web application is for a youth club basketball team. I can add players with an image and their information. I can add leagues with each league having many games. I can add albums with each album containing many photos. I have a calendar that shows the current month that I can add events to which will show up for that day. I can add stats for each player that corresponds to a game. I add basic stats and the model does the calculations for individual and game stats. I am currently working on adding videos to my web application. I've used plugins and gems. I'm also learning and using CSS. When I encounter a problem I search for a solution, which can happen in a day or a month. This is FUN!

I wasn't actually on the computer all day, it just seems that way. I took some time to watch the Blue Angels. I took a couple hours here and there to go watch my nephews play basketball and football. But then I'm back on the computer. So much fun.

Saturday, October 2, 2010

The Process of Finding Standout Ideas

How do you know if you have a blockbuster idea? As an example, is my Trading Journal idea a standout idea?

Some people have said to "just get started" on your idea and you'll discover if it's a blockbuster idea. Is that the best move? I read an article The Idea Virtuoso... that touts the process that university professors of research labs use to find the best idea. Having deep knowledge and expert feedback can differentiate between mediocre and great ideas. This reminded me of Dr. Johnson being awarded a grant to research the smart grid. What was his process to settle on that idea to get awarded that grant?

It seems like meeting with a group or team to brainstorm and discuss all ideas are needed to identify the best possible projects before getting started. This commitment to understanding the idea and seeking feedback will help you follow ideas you feel have a strong possibility for success.

It's called the idea-centric approach. You research your ideas to discover if there is an audience out there that sees value in an idea. When the standout idea emerges, the focus of your efforts goes toward implementing that idea. In this approach, you need to learn or know the field and seek expert advice.

Monday, August 9, 2010

Adding Video to my Rails Web Application

My Rails web app has been going well. I've been able to figure out some things and get them to work. My current task is adding an upload and convert video function. I want to shoot video then edit the video and upload the video to my web app. I consulted google and was told FFmpeg was the way to go. FFmpeg is a complete, cross-platform solution to record, convert and stream audio and video. I consulted google on how to combine FFmpeg with Rails and was lead to Converting Videos with Rails: Installing FFMPEG. The problem is, this is an example of how to install FFmpeg on Ubuntu. I don't have Ubuntu. I'm on Mac OS X 10.4. I found Installing and Using FFmpeg on Mac OS X and followed the instructions with no success. This is where I'm at and what I'm doing.

Monday, May 10, 2010

Check - It Works!

I figured it out. I have attributes in my Stat database table that the user doesn't provide input for. The value, for the hidden attributes, is gotten from the other attributes that the user does provide input for.

What I did:

In the Model:

before_validation :cache_virtual_columns
def total_points
((twopfgm * 2)+(threepfgm * 3)+(ftm * 1))
end
def field_goal_percent
sprintf("%0.3f", ((twopfgm+threepfgm)/(twopfga+threepfga.to_f)))
end

private
def cache_virtual_columns
self.total_points = total_points
self.field_goal_percent = field_goal_percent
end

In the Form:

%= f.hidden_field :total_points
%= f.hidden_field :field_goal_percent


When a new Stat record is created, it checks the Model and before doing validations does the cache_virtual_columns method. cache_virtual_columns has the total_points and field_goal_percent DB columns equal the value in their method. This updates the Stat record to contain values for each attribute.

Thursday, May 6, 2010

“Always two there are, a master and an apprentice.”


I'm having a blast hacking away on my project. Rails is a fun language to learn. Lately I've been hitting a wall on the execution side. I will be working and get to a point where everything I do isn't working. I know what I want to implement and have an idea of how it should be implemented but nothing seems to work. I run searches to find an example of what to do but come up empty. Things get dark when I am unable to figure it out.


Here's my dilemma, I have a form for a user to enter stats. The user enters 2 point field goals made/attempted, 3 point field goals made/attempted, free throws made/attempted, offensive/defensive rebounds, and others. I have other model attributes that the user doesn't provide input for on the form. They are total points, field goal %, 3 point field goal %, free throw %, and total rebounds. I'm thinking the model can take the attributes the user entered, obtain certain values and perform the calculations to populate the extra attributes all before the record is saved.

For example, to calculate the points scored for the current stat record being created;

# before record saves, do total_points method

before_save :total_points


# calculates total points of current record

def points

@twopoints = :twopfgm * 2

@threepoints = :threepfgm * 3

@onepoints = :ftm * 1

@twopoints + @threepoints + @onepoints

end


private

# update :total_points attribute of record with points

def total_points

stat.update_attribute(:total_points, points)

end



This doesn't work. I'm in the process of figuring this out.

Sunday, May 2, 2010

To Boldly Go Where No Man(Me) Has Gone Before

Captain's log, Stardate 542010.5.

I've been working on my project for week's. The past couple days have been uneventful but I've made excellent progress. I am figuring out the relationships between League, Game, Player, and Stat. I've been learning about nesting resources and nesting models in one form. I've split them into pairs.

League has many Games. Game belongs to League.
Player has many Stats. Stat belongs to Player.

This gives me these routes.

/leagues
/leagues/:id
/leagues/:league_id/games
/leagues/:league_id/games/:id
/players
/players/:id
/players/:player_id/stats
/players/:player_id/stats/:id

Now I am able to create a league with many games and players with many stats. I'm working on getting the players with their stats to belong to a specific game in a specific league. I want to access players on its own so I'm hesitant to nest it. Plus, Rule of thumb: resources should never be nested more than 1 level deep. So I shouldn't do Games to Players to Stats.

I would like to have the form below to create the box score for each game. It will also track each players stats.
It would start with a drop-down menu to choose league. Selecting a league will activate the drop-down menu of games in that league. Selecting a game will do something that will allow me to get the form to choose a player from a drop-down menu and add their stats for that game. And do this for multiple players.

When I view the game I see


May the force be with you.

Tuesday, April 27, 2010

Secret Society of ...

Greetings to All of my Followers ... both of you ... whom I follow more

Hope all is well in your kingdoms.

I call to order the meeting of the Hackers Guild.

Take your seat at the round table.

First order of business, the rules. The first rule of Hackers Guild is you don't talk about Hackers Guild!

Now repeat the mantra:
I don't know who you are. I don't know what you want. If you are looking for ransom, I can tell you I don't have money. But what I do have are a very particular set of skills; skills I have acquired over a very long career. Skills that make me a nightmare for people like you. If you let my computer go now, that'll be the end of it. I will not look for you, I will not pursue you. But if you don't, I will look for you, I will find you, and I will hack you.
I've been locked up in my room hacking away learning what works and what doesn't work with Rails. I've gotten close with google searching, Stack Overflow, and the API's. I've made friends with different gems and git and github for plugins. I'm learning a lot and getting things to work. I just don't know if it's the best way. I got file upload for images working but not for videos. I got authentication up and running. I got a calendar to contain events.

This is all my deliberate practice to learn what I need to implement my own software. My current task is implementing a basketball stat tracking system for one team with a group of players. I've broken it down to 4 models. The models are League, Game, Player, and Stat. I will be able to create a new League that will contain many Games. Each Game will contain the Stats of each Player for that Game. Similar to a box score but only one team. I also want each Player view to show the career stats for each league or year. I'm working on figuring out the relationships between the models. That will help with the routes. I'm also figuring out how to handle fields that require calculating two or more attributes to get the value. Like field goal %, you take the number of field goals made divided by field goals attempted to get the value.

This is my focus.

Is there anything else to discuss?

This closes the meeting of the Hackers Guild.

Live long and prosper

Tuesday, March 30, 2010

Social Networking

I am now on Twitter, Facebook, TechHui, and Blogger. I have no idea what to do with them all. How do I utilize them and for what purpose? Facebook asks "What's on your mind?" Twitter asks "What's happening?" TechHui asks "What brings you here?" Are random thoughts alright? It seems like the way to keep friends and family up to date. I guess I'm still trying to find my voice. What do I want to say?

Friday, February 19, 2010

Practicing Hacking

I am a big believer in deliberate practice. I've done my research and understand the concept. It is "activities designed, typically by a teacher, for the sole purpose of effectively improving specific aspects of an individual's performance (Anders Ericsson)." It's designed to improve performance, it's repeated a lot, feedback on results is continuously available, it's highly demanding mentally, it's difficult, and it requires specific goals.

Integrating Deliberate Practice

Deliberate practice seems straightforward, but I'm having a difficult time integrating it with learning a programming language. I have no problem implementing deliberate practice with sports or playing a musical instrument. These fields have better rules and objectives when measuring success. It is clear to me on how to improve performance for these fields.

If I wanted to improve my dribbling in basketball I would practice with one hand at a time standing still then while moving slow then by moving fast. After I improve I would increase difficulty.

If I wanted to improve in playing the guitar I would practice each chord individually and then practice transitioning from one chord to another.

Knowledge Work

The previous fields are more on the physical side. Learning a programming language is more knowledge work. How do you optimize performance on knowledge work? I'm trying to figure out a systematic approach for building a deliberate practice strategy for learning a programming language.

My Current Process

I am in the process of learning Ruby on Rails. I want to build web applications. I've been hacking on my application getting things done and figuring stuff out but I do not feel I'm becoming a expert Rails programmer. As soon as I solve my task I have forgotten the process I used to figure it out. I see the finished code but cannot quite remember what searches I did that yielded results and what searches didn't. I also wonder how to repeat the process to deliberately practice that new solution. And if my solution is the correct way to do it.

Will building applications and continuous hacking create an expert programmer?

Saturday, January 9, 2010

Self learning

Self learning has been challenging. Building my blog website application from scratch has been fun but has not been the smoothest experience. I know what I want to implement and need to work to implement the features. The problem is that the work schedule is in my head and not written down. My focus is jumping from one thing to another thing. I'll be working on the layout of the comments and notice something in the comment form I want to improve and switch jobs. And neither one gets fixed. I will be figuring out a schedule of work to do and follow it.

Tuesday, January 5, 2010

Adding Date and Time to my Rails Blog App

For my blog posts and comments I wanted to display the date and time. Fortunately, the models automatically add the attribute created_at of datetime during the migration to the database. This allows me to just call the created_at attribute from the posts and comments table to display them after they have been created.


I got my first problem when I added it to my view. It appeared as 2009-12-14 08:25:51-1000. That's not what I wanted. I wanted December 14th, 2009 8:25AM. And this gave me another problem, the time was 10 hours off. I wanted Hawaii time so it should have been 2009-12-13 22:25:51-1000.


After a lot of searching I was able to piece together a solution. I have rails 2.3.3.


To format date and time I modified config/enviroment.rb. Looking at this file I found config.time_zone = 'UTC'. I didn't know what UTC was but above it had Run "rake -D time" for a list of tasks for finding time zone names. So I ran 'rake -D time' in my terminal and was given 'rake time:zones:local' which I ran and was given Hawaii as my time zone. So I changed config.time_zone = 'UTC' to config.time_zone = 'Hawaii'. This gave me my date and time but not the right format.


I wanted December 14th, 2009 8:25AM. To get this I had to create my format. I eventually found rails module for conversions. I then had to figure out what %Y-%m-%d meant. When I found the meaning I wrote the code below to display my date and time format. I also found to get 1 to display as 1st, 2 as 2nd, 14 as 14th, 23 as 23rd I had to add ordinalize to the day.


ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(

:time => '%I:%M%p',

:date => lambda { |time| time.strftime("%B #{time.day.ordinalize}, %Y") }

)


Format Meaning

%a The abbreviated weekday name (“Sun'’)

%A The full weekday name (“Sunday'’)

%b The abbreviated month name (“Jan'’)

%B The full month name (“January'’)

%c The preferred local date and time representation

%d Day of the month (01..31)

%H Hour of the day, 24-hour clock (00..23)

%I Hour of the day, 12-hour clock (01..12)

%j Day of the year (001..366)

%m Month of the year (01..12)

%M Minute of the hour (00..59)

%p Meridian indicator (“AM'’ or “PM'’)

%S Second of the minute (00..60)

%U Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)

%W Week number of the current year, starting with the first Monday as the first day of the first week (00..53)

%w Day of the week (Sunday is 0, 0..6)

%x Preferred representation for the date alone, no time

%X Preferred representation for the time alone, no date

%y Year without a century (00..99)

%Y Year with century

%Z Time zone name

%% Literal “%'’ character



In my view I added:


%= comment.created_at.to_s(:date) %

%= comment.created_at.to_s(:time) %


Now every post and comment has a correct date and time.

Thursday, December 17, 2009

Keola's Blog Application

For the past 16 days I’ve been hacking away on my blog application. My goal is to go from development to production. I want to get version 1.0 online by February 1st. I’m not quite sure what’s involved in taking a website public, but I am going to find out.

The site will be a two-column layout containing a header, navigation, content, sidebar, and footer. The navigation bar will have a home, about, contact, and blog page.

The blog engine is similar to the “creating a weblog in 15 minutes with Rails 2” screencast with a few minor tweaks. I added a few more attributes to the comment model to get a name, email, and website.

I also am building this application without using the scaffold to generate things. I want to understand the Rails convention. I want to fill out the controllers, views, routes and whatever else is needed. It’s running, so I’ve been pretty good about adding what is needed.

The past couple weeks have been fun. I’ve gotten further along then I planned. Everything is flowing. Next I will share some things I discovered.

Tuesday, December 1, 2009

Taking Action - Start to Finish

Imagining something you might like to have or do is a dream. A dream written down and clearly visualized is a goal. A tangible, measurable step written down and committed to is an action. You will not achieve a dream if you don't systematically work through the actions that lead to the goals that lead to the dream.


It's easy to get passionate about setting goals. We all get excited about our dreams. Taking consistent action on them on a daily basis until they are done is another story. How do we stay motivated with the same passion and excitement to follow through on the everyday tasks required to achieve the goals? How do we overcome any obstacles that occur?


Whenever we conceive the goals we want to achieve, we each enter our own process to accomplish these goals. My process involves imagining my goal as a finished product, researching and planning by gathering information to be prepared to work on the goal, and taking action to achieve the goal while maintaining the passion and self-discipline to follow through to the end result.


I have noticed that I easily get distracted and stuck in the researching and planning phase. I'm always looking for more and more information, but rarely implement what I've already learned. I am acknowledging that there are profound barriers between reading and DOING. I know that the solution isn’t “more,” but actually using the knowledge I've gained. I need to get to the action phase sooner. FAILURE is OK! I'll be learning while doing.


After taking action there is always an obstacle or two that try deter you from reaching your goal. At this point it becomes difficult and the excitement fades. This is when the self-discipline needs to kick in. I use my ability to be resourceful and work on solving the obstacle. If I'm having trouble figuring out how to overcome the obstacle, I seek out help. Two people are better then one and three people are better then two.


Today is the day I begin taking action. I've been learning Rails for a couple months and am still researching and planning. All I've been doing is reading up on Rails, CSS, and XHTML as well as following a bunch of tutorials. I haven't even started my own application. I've worked on a store application which had a buyers side with a shopping cart and a sellers side to handle the products and sales. I worked on a digg like application where users could submit articles and vote on them and view the most popular ones. I've done many different blog applications. And many more tutorials. Today I start hacking on my applications and less on tutorials. Maybe even find someone else's and contribute to it.


My dream is to create a website with all my web applications. My first goal is to create a blog for my website similar to the ones I read everyday. My actions will be to build the blog beyond what the tutorials teach.