Skip to main content

Mobomo webinars-now on demand! | learn more.

This post is part of a series called Open Source Citizenry in which we discuss ways to eliminate the barriers that developers and companies face to fully participating in the open source community.

You might think there's not really anything to being a good user of open source. Install the library, use it how you need it, and move on. And honestly, for the most part that's a fine thing to do. But if you want to be more than one of the silent users, if you want to help the projects you use just by using them, there are lots of ways to do it. You could become a vital part of pushing forward your favorite open source projects without ever altering a single line of code.

Ultimately, being a good open source citizen is about respecting what open source is, how it's made, and how you can help. Open source software is made by many; that's its beauty and its curse. If you can help bring more order to the naturally chaotic development process by adding documentation, fielding support requests or even just encouraging maintainers to keep going, you are becoming a vital part of the open source ecosystem and helping it to grow.

Categories
Author

As someone who has both attended and instructed many 2-5 day classes on programming topics, I’ve come to understand there are certain things teachers can do to make classes more useful and enjoyable.

Here are 12 tips to keep in mind when creating and teaching a technical course:

  1. Rest- I’ve learned to make sure I get plenty of rest the night before I teach. I also make sure I have plenty of caffeine, water, and healthy snacks at my disposal during the day. Do not underestimate how much energy it takes to run a class.
  2. Relax- You lose your train of thought, you freeze, you stutter, you sweat a little, you don't know the answer, you forget their names... Relax, these things happen. Believe it or not, your students want you to succeed and are very forgiving. Just realize that mistakes happen: handle it, and move on. If you can't recover quickly, simply make the class take a 5-10 min break to recover or defer to the other instructor.
  3. Break the Ice with Introductions- For me, the hardest part of teaching a class is the first hour of class on the first day. You don't know the students and they don't know you. The best way to get around this is to quickly introduce yourself then have the students go around the room and introduce themselves. "Please tell us your name, where you're from (location, work), what's your specialty, and what you hope to get out of the class". This takes the pressure off you, distributes it across everyone in the room and gives you the time to get comfortable and ease into the role of instructor.
  4. Labs- Lots of them. Labs are the most important aspect of teaching a class on programming. Students will not absorb the information from your lectures as well if you don’t give them frequent opportunities to put the material to use in a practical way. It's like playing a musical instrument - you can read about it all day long but when it comes down to making music there's no substitute for physical practice and interaction with the instrument itself. Knowledge is solidified during lab time. This is when most of the "Ah-ha!" moments occur.
  5. Avoid Slides if Possible- Slides work really well for short presentations because they help support your succinct message; in the classroom, slides can actually hinder students from paying attention. Slides also have a tendency to kill the opportunity for spontaneous subjects. It's okay to go off on a tangent, especially if your students are engaged. Don't just read from a slide deck. Build things with them on the fly. There's nothing techies love more than live, working, and tweakable examples. Student: "How does that work? Why does that work?" Instructor: "Here, let me show you". That wins over slides every time.
  6. Encourage Discussion- People like to talk. Give them frequent opportunities to talk with you and the other students about the material. I've found that if you encourage lots of discussion during the lecture (and throughout the course) people tend to help each other a lot more during labs. It creates a more lively and memorable environment. People pay attention more if an interesting conversation is likely to break out at any time.
  7. Two Is Better Than One- Even if your class is small, it’s always better to have at least two instructors. One instructor can do most of the lecturing while the other can ask questions, point out typos, play devil’s advocate, gauge the students' engagement levels, and pay attention to the pacing. The secondary instructor can also walk over and help individuals while the primary is interacting with the rest of the class, ensuring a consistent flow. If one of the instructors gets flustered or loses their train of thought the other instructor can take over or help get things back on track.
  8. Contextualize- Structure your class so that each topic builds on the previous one. Lay out a foundation and build upon it. Stick with the same application or domain space throughout the course. Put some thought into the transitions between topics in your curriculum and lay it out in a way that is comprehensive and progresses logically and predictably.
  9. Legos- During the lectures and the labs you are giving students small building blocks of knowledge and inspiration. Don’t forget to give your students the chance to build something. Decide on an appropriate application to build throughout the course. This will help to solidify the knowledge and put those Legos to good use.
  10. Break Often- It’s easy to get rolling on an activity or topic and forget about taking breaks. Set a timer for yourself if you have to because your students need plenty of opportunities to go to the bathroom, grab water, refill their coffee cups, stretch and socialize for a few minutes at least every hour. Pay attention during breaks; you'll quickly learn if people are having a good time or not. Be aware of mass exodus or silence.
  11. Continuing Education- Make sure students learn enough to ask the right questions when they finish your course. Make sure you’ve taught them well enough so that when they try to practice the material a week later at home, they know how to ask the right questions, look in the right places, etc. Give them the equipment they need to succeed once your class is over.
  12. Post-Course Availbility- Don’t disappear when all is said and done. Make sure your students know how to get ahold of you. Encourage them to seek you (and each other) out if they have questions or concerns. Ask them for feedback about the class. Create a Google Group so they can ask questions about the concepts after the class is done. This allows them to have access to you and the other students.

With these tips you should be well equipped to deliver a quality and exciting class that your students will talk about and remember for years to come. Teaching programming classes is an act of servitude, and one that is highly respected. Taking the time to create an engaging curriculum and a thoughtful structure will be of great benefit to you and everyone else.

Those that know, do. Those that understand, teach.

Aristotle

tl;dr

The format I've used which seems to work best (to keep folks engaged and encourage knowledge solidification) is:

For each topic:

  • 30-40 mins of lecture
  • 15-30 mins of lab/exercise
  • 10-20 mins of discussion of different solutions
  • 5-10 mins break
  • Encourage lots of questions and discussion throughout all sections
  • Always have a minimum of two instructors
Categories
Author

In the second post in the series on “Why Your Company Needs a Rails Shop”, we’re talking about the “first-mover advantage" and how outsourcing your development to a Rails company can get your product to market quicker.

What’s The Big Idea?

You’ve got a great idea. You know it’s great because you’ve done objective market research, talked to your target customers and made an effort to understand your competition. Now you need to get your product some legs of its own. Getting your product to market as soon as possible can be critical to the success of your initiative. The web is rich with the innovations of passionate people; the landscape is competitive. You have no time to spare.

Advantages of being first to market:

  • Monopoly – Not the game, but rather a temporary monopoly of the market share. Being first to market in your niche means that you have the early advantage of being the only (or one of the few) players in your field, allowing you to capture a market share advantage.
  • Good Looks – Being the first implies that you are innovative and proactive. You were smart enough to detect an opportunity and adept enough to act on it quickly. Getting to market quickly saves you from the “me too!” reputation that your future competitors might garner when they penetrate the market with a similar idea or product after you have paved the way.
  • Experience – By getting to market first you get a head start on building experience with your customers, the technology, the feedback, and engagement of your product or service. This early experience is valuable when you use it to fine-tune your product and continue to release new versions or features. The early experience gives you the opportunity to foster exclusive and meaningful relationships with your target audience before anyone else.

Who You Gonna Call?

A Rails shop! When you need to get to market quickly, go with the pros. In last week’s article in this series we talked about how difficult it is to penetrate the competitive Rails market to find good talent. When you need a web application created quickly and professionally it makes even more sense to rely on an experienced Rails shop. Spending weeks or months trying to build an internal team will only delay your product launch.

Trying to hire your own team can be costly and time consuming when you consider this:

  • Finding good Rails developers and verifying their experience level is no easy task. Ruby is a young language and Rails an even younger framework. This means that most Rails developers have only a few short years (sometimes months) of experience under their belts. Additionally, you might not know what to look for in a Rails developer, whereas Rails companies have experience vetting good programmers.
  • It can take 2-3 months to hire experienced individual Rails programmers and assemble a small internal team of developers.
  • Even after you’ve hired a good internal team, you won’t necessarily have an expert Project Manager on hand who is skilled in Rails to lead and direct the team.
  • Assembling a team from scratch means that you don’t know how the new team members will work together. You have to allot time for personality and workflow differences as the team adjusts to working together.
  • Hiring a team internally leaves you with the added cost and concern of providing benefits and having additional employees on your books indefinitely. In hiring a Rails shop you negotiate a straightforward contract for work and then you have a choice of keeping them on retainer for future maintenance if needed.

As a Rails shop that’s been around for awhile, we’ve learned a few things about hiring Rails developers, working with clients efficiently, and delivering projects on time. Rails shops are living in the Rails world every day – we understand the ecosystem, and can easily identify a talented Rails programmer. When you outsource your web application development to a Rails shop you’re inheriting the combined experience of a large team of experts. And when you need to get your idea to market, you need the power of experts to help take you there.

Full Service

Most of the popular Rails shops in the U.S. today offer a range of services to meet all of your application development needs. This mean that when you hire a full-service Rails shop you’re getting an entire team of experts to manage your application every step of the way:

  • Designers – A team of experienced designers who are adept at listening to clients and transforming their vision into beautiful design and optimal layout.
  • Developers – Expert Ruby on Rails developers who have been building web applications in Rails for years, and have key knowledge of the newest technology and advancements in the industry.
  • Project Managers – Someone to oversee and direct the development process of your product, ensuring that deliverables are defined and met on time, and that the team is meeting client expectations every step of the way.
  • QA Engineers- Skilled software testers that put your application through rigorous testing before it ever goes live, ensuring that the final product is secure and ready for users.

Rails Company + Your Product = Win

We all want to win. And it's easier when you partner with people that have a track record for success. Taking your vision to a reputable Rails company means that you get the assistance of a team of seasoned Rails developers, designers and project managers – all ready to listen to you, understand your intent, and breathe life and form into your vision. Having a Rails shop to work with ensures that you can get your application launched sooner. Plus, you’ll have a team on hand that is already experienced with your product when you need to work on the next iteration to keep you competitive and fresh.

About Intridea

We create custom web and mobile solutions for businesses large and small across a range of industries – from Healthcare, Government, IT, Education, Arts, Real Estate, Insurance and more. Our team of designers, architects and developers can work with you every step of the way to bring your vision to life on the web. Contact us today to find out more!

Categories
Author

Our developers tend to have interesting conversations throughout the day in Socialspring Stream, our communication and collaboration application. It occurred to me today that it would make sense to take some of the useful tidbits of information that surface there and share them with the rest of the development community! After all, the conversations are captured already - all I need to do is bundle up the relevant bits of information and serve them to you via our blog; in other words, expect more quick posts of tips and tricks here!

Fast Project Searching With Ack

You can set ack to be grep within vim, in order to make searching within your project faster and more effective. It’s a great programmer search tool. Here’s how:

  • Install ack (instructions found here)
  • Then in your .vimrc file “set grepprg=ack”.
  • Then whenever you “:grep ” vim will use ack instead of grep!

Why would you do this? Because its so much faster! BetterThanGrep cites these reasons (among others) in this list on their site (full list here):

Top 10 reasons to use ack instead of grep
  • It's blazingly fast because it only searches the stuff you want searched
  • ack is pure Perl, so it runs on Windows just fine. It has no dependencies other than Perl 5.
  • Searches recursively through directories by default, while ignoring .svn, CVS and other VCS directories.
  • Ignoring .svn directories means that ack is faster than grep for searching through trees.
  • Which would you rather type?
    • $ grep pattern $(find . -type f | grep -v '.svn')
    • $ ack pattern
  • ack ignores most of the crap you don't want to search
    • VCS directories
    • blib, the Perl build directory
    • backup files like foo~ and #foo#
    • binary files, core dumps, etc

Today's Vim tip was brought to you by Adam Bair, who was giving another developer advice on grepping over a project directory. Check back often for more tips, or follow us on Twitter for timely notifications about similar tips and tricks!

Categories
Author

When I was developing the Presently Android client I ran into an interesting problem. If a user is in the main timeline activity and a new message comes in, the active timeline just needs to update with the new message. However, if the user is in another activity stream, (like viewing @ replies or DM's for example) and a new message comes in to the main stream the application should not only update the main stream but should also show the user a notification so they can be aware that new messages are coming into another activity.

In this post I will show you how I solved this problem.

There is a background service to pull new messages from the server. When the service receives a new message, a broadcast will be sent:

Then, we have a BroadcastReceiver in TimelineActivity to receive the broadcast.

Now, when new messages come in the user can see the messages update to listview and get a notification in the status bar. But there is a small problem: it only works in TimelineActivity, because when the user opens a new activity or presses the Home button, the BroadcastReceiver is unregistered in the onPause() method.

So I tried to put the register/unregister operation in the onCreate()/onDestroy() methods. This fixed the problem of new messages and notifications not showing in other activities. But then there was another problem: in TimelineActivity, the user receives an additional and unnecessary notification. So I set out to fix this particular problem.

The first question I asked myself was, “Can I only use one BroadcastReceiver?” The answer was “No!” So, I used two BroadcastReceiver(s) to fix this problem.

In this code there are some key points I want to outline:

  • Broadcast the new messages with sendOrderedBroadcast() instead of sendBroadcast(). It will be passed one by one unless you stop it by abortBroadcast().

  • Register/unregister RefreshTimelineReceiver in onResume()/onPause(), and RefreshTimelineAndNotifyReceiver in onCreate()/onDestroy(). This makes certain there is no RefreshTimelineReceiver in other activities.

  • Give FILTER_HIGH_PRIORITY to RefreshTimelineReceiver and FILTER_LOW_PRIORITY to RefreshTimelineAndNotifyReceiver. In TimelineActivity, RefreshTimelineReceiver receives the broadcast first.

  • AbortBroadcast after showNewMessages() in RefreshTimelineReceiver. Don't pass the broadcast to next receiver.

And this is how I solved the problem of notifying a Presently Android user of new incoming messages to the main activity if they are active in a separate activity stream. Hopefully this might help someone else out who might be working through a similar problem!

Categories
Author

We know there is an Application class in the Android api and according to the class name it's used for global settings or running entrance. What does it to do for an application? I will dive into it along with some examples in this blog post.

In the Android reference it describes the Application class: "Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created."

So you can create your own subclass of Application like this:

And specify its name in your AndroidManifest.xml's tag

The Application class is mainly used for some Application level callbacks and for maintaining global Application state.

Application level callbacks

  • onConfigurationChanged( ) Called by the system when the device configuration changes while your component is running.
  • onCreate( ) Called when the application is starting, before any other application objects have been created.
  • onLowMemory( ) This is called when the overall system is running low on memory, and would like actively running processes to tighten their belts.
  • onTerminate( ) This method is for use in emulated process environments. It will never be called on a production Android device, where processes are removed by simply killing them; no user code (including this callback) is executed when doing so.

Maintaining global Application state

Sometimes you want to store data, like global variables which need to be accessed from multiple Activities - sometimes everywhere within the application. In this case, the Application object will help you.

For example, if you want to get the basic authentication data for each http request, you can implement the methods for authentication data in the application object.

After this,you can get the username and password in any of the activities like this:

And finally, do remember to use the Application object as a singleton object:

Categories
Author

It's been close to a year since Rails 3 came out and I've had the pleasure of working on several Rails 3 projects since its release. Some existing gems became irrelevant with the release of Rails 3, while others lived. Additionally, we've seen many new gems come to life. I'd like to share a stack of gems that I've been using this year. Hopefully they will give people a bit of help while developing a new Rails 3 app.

Most of these gems have good documentation on their project wiki (every great gem should be well documented, right?), so I won't go into great detail about the mechanics. Instead, my aim is to introduce you to some of the gems I find most useful and separate them into meaningful categories, as a sort of reference guide.

Here we go:

» Authentication

The above two are really amazing gems for speeding up your authentication. Yes, I love both of them in different cases: ideally, OmniAuth is better for applications which want to support multi-provider external authentication, which is why I've just added OmniAuth into the RefactorMyCode Rails 3 branch to take advantage of its auth benefits. Devise is totally powerful enough for the classic authentication case. However, if you have too much business logic inside your login/registration/auth flow, you definitely need to make your own authentication.

» Access Control

Ryan is a star in the Rails world, so naturally his CanCan gem is really popular, but with good reason: it does really powerful authorization. However, declarative_authorization is also a good option. In fact, Ryan mentioned CanCan was inspired by declarative_authorization.

» Views/Page and Admin Scaffold

From a front-end perspective, I suggest you might want to try the above gems to speed up and simplify your UI design process. For example, rails_admin gives you a nice interface to manage your application's data.

» Quick SNS

These gems will allow you to prototype the basic functionality of your application quickly without having to worry about creating everything from scratch - so you can focus more attention on the meat of your application instead of the nuts and bolts.

» Form and Related Tools

Most of the above gems are famous through RailsCasts. There are two pairs of options here: simple_form and formtastic or paperclip and carrierwave. I like all these solutions, and you should pick the one that fits your project. If you want to know the differences between each pair, get more details on their wiki :) tiny_mce is an HUGE gem for rich editing; I list it here to remind you that it exists, but I recommend you get the WYSWYG via a JS lib like CLEditor - it works gracefully.

» Search Solutions

In regards to search in Rails, I bet there are some strong opinions out there. I want to split these gems into two types: Object-based searching and Full-Text searching. I highly recommend you use meta_search and/or meta_where for object-based searching because it can convert your form params directly to a search solution which is super convenient. Full-Test searching depends on your use-case, but all these three gems (thinking-sphinx, acts_as_indexed, sunspot) are great.

» Pagination

Yeah, you can use will_paginate in Rails 3, but I will suggest you should give kaminari a try, that's really cool.

» Background Work

These are two projects that accomplish basically the same thing. There is a post that introduces resque clearly here. In the post, the Github staff mentions their brief history of doing background jobs and they do a good job at highlighting the differences between the two.

» Status Machine

I like to use workflow a bit more than state_machine, since it's more natural to me. You definitely need one status machine to control your stable flow stuff, such as a registration flow status or a wizard-like features.

» Rack API framework

This gem is for adding REST-like APIs to your Rails/Sinatra application. Michael gave an awesome presentation at RubyConf2010 on Grape; I recommend watching it to see the greatness of Grape for yourself. I believe you will fall in love with it.

» Memcached Client

These two gems are actually mainly written by one same author Mike Perham. He mentioned that Dalli is a high performance pure Ruby client for accessing memcached servers. It works with memcached 1.4+ only as it uses the newer binary protocol. It should be considered a replacement for the memcache-client gem. The API tries to be mostly compatible with memcache-client with the goal being to make it a drop-in replacement for Rails.

» Deployment and Monitoring

I am not a system administrator, so I can't speak with any authority on this. That said, I do find these three gems come in handy with deployments and monitoring.

» Cron job and Backup as a Pro

These two gems are my favorites! Before I knew about these, I had to write complex and stupid scripts to do backups that I was not familiar with. Cron job is also a pain if you are not a system administrator. Now time changes and you, as a Ruby programmer, can do the cron job and backup in the Ruby way, surely as a PRO. :)

» Testing Gracefully

Testing is always important, and with the popularity of testing practices like TDD and BDD you have to own your super gun to play. These gems can help you out, although I didn't cover all the different levels of testing with these gems. But I will say, rspec is my favorite framework for testing, and factory_girl and faker are good supports. Anyway, test by your own way.

» Toolkit

There are many handy gems which will give you convenience and power. Take the above four as examples: "Ruby-Debug" lets you easily check your running application's context at specific program points; "Hirb" displays your AR items conveniently in a table view in console; "Cheat" brings tons of other gems' manuals into your terminal window for easy reference and; "Rails-Settings-Cached" is for global configurations in Rails 3 applications. Yeah, throwing the brick out is to meet your GEMS.

How to find great gems?

First, you need to follow Ryan's railscasts; he is good at introducing new stuff via video. Second, you can go through the GemFile of a great open source project that you love - this is definitely the best way to come across valuable gems. Third, just subscribe to github ruby trends to know what's going on in Ruby/Rails community. There are also some other good sites, like rubygems and railsplugins, where you can find useful gems with some poking around.

I originally shared this topic with all of the Intridea East Team members during our weekly Friday Tea-hour. You can find the PPT here. I wanted to share the list with more people, so I turned to our blog for that purpose. I'm sure I missed many valuable gems, so please share your thoughts in the comments!

Categories
Author

It’s been nearly a year since the release of the iPhone 4, and much to the dismay of the tech community, it’s still the only product in the Apple lineup with a high pixel density ‘Retina’ display. While the much-hyped feature drew universal praise when the device was unveiled, some were wondering the following:

  • Would consumers see this as a compelling feature?
  • Would competitors follow suit, establishing critical mass for high PPI displays?
  • Would Apple eventually launch a Retina display for iPad or Macbook Air? Or would another manufacturer release an ultra-high resolution tablet or laptop?

In a little over 10 months time, high PPI displays are currently everywhere in mobile. Walk into any carrier retail store, and chances are that the featured smartphones already feature high-resolution displays. Those that don’t have them likely will within an iteration or two.

Retina display for Mac will be here sooner rather than later. Apple’s yet-to-be-launched OS X Lion includes built-in support for the Retina display, along with ultra high-res desktop wallpapers and icons. It’s a decent bet that we’ll eventually see some variation of the Retina display across the entire product line. And of course, as happened in mobile, the rest of the industry will follow Apple’s lead, effectively eliminating the concept of a default dpi standard.

How can designers and developers prep for this change?

Embrace resolution-independent design practices for the web, not just mobile. Up until this point, designers and developers who haven’t worked in mobile have been able to avoid the extra hassle of prepping content for high PPI displays. But with the classic notion of the ‘pixel’ fading away, it’s a good time to reiterate the importance of resolution-independent design practices across the board. Specifically:

  • Minimal use of bitmaps (reserved for photography, video, and illustrations)
  • CSS3 for buttons, gradients, shadows, and lines
  • HTML5 canvas and SVG libraries for complex and interactive graphics
  • @font-face for custom type
  • Vector graphics for interface elements

Start to use Scalable Vector Graphics (SVG) on the web. With Internet Explorer 9 finally getting onboard with the basic SVG feature set, it’s time to adopt vector graphics on the web (for real this time). Unless you are designing for a specific audience using certain browsers (in which case you may need fallbacks), now is a great time to consider using SVG for:

  • Icons
  • Background images
  • Custom type treatments
  • Logos and mastheads

Get comfortable with Adobe Illustrator. This advice was doled out around the web when the Retina display was first introduced, and one year later it rings more true than ever. Photoshop is still the industry standard for producing web graphics, but as the web steers towards resolution independence, so should the toolkit.

Photoshop users: keep all of your source files in vector format for as long as you possibly can. If you must use Photoshop (full disclosure, we love it and use it daily at Intridea), it’s a good idea to create your interface elements as vector Smart Objects, or import them directly from Illustrator. This way, your elements can scale when you resize the source files without effectively losing resolution.

For time being

The current process of designing for high PPI displays is a bit of a hassle, but it’s hopefully transitional. Designing for the Retina display with targeted CSS and high-res bitmaps is already intensive. Throw in the eventual release of high PPI displays on tablets and laptops and it’ll be painstaking.

There are a number of established design practices for supporting high PPI displays. Many of the tutorial articles written soon after the iPhone 4’s launch are still relevant (here’s a great list of some key takeways).

Categories
Author

No matter what level of developer you are, at some point you will have the underrated joy of inheriting a legacy software project. And since we're fortunate enough to work in such a fast-paced community and ecosystem, "legacy" really encapsulates any piece of software more than a month or two old. Often though, we don't have time to appreciate how our ancestors used to write Ruby back in the days of Rails 2.3, or even (gasp) 2.1 — we need to get right to work. It's at this point that the nefarious Jabberwocky method can rear its ugly head.

The Jabberwock in the Room

When we first adopt a project, some of the language may seem like gibberish. Let's say we encounter this snippet of code in some controller:

@sword = VorpalSword.new @sword.snicker_snack! 

Looking at this code, we might expect to open up the VorpalSword model and find:

def snicker_snack!    Jabberwock.destroy_all end 

Unfortunately, in this all-too-contrived example, the VorpalSword class simply doesn't have that method!

The Jaws That Bite, the Claws That Catch!

Stuff and nonsense! Now we'll have to dig through and see if we can find a way to uncover this method. Let's start doing some sleuthing...

  • Maybe there's a method_missing in the VorpalSword class

  • Does VorpalSword inherit from anything?

  • Hmm...does it include or extend any modules?

  • It's probably just a plugin. Let's check the vendor/ folder...

  • Okay, maybe not. How about something under the lib/ folder...

  • Is "snicker_snack!" a gem?? Who would name a gem "snicker_snack!"

  • Did someone overwrite method_missing in ActiveRecord::Base?!

  • That's it, I'm switching to Scala!

Final Uffish Thoughts

Abstraction is a fantastic technique - we love to keep our software DRY and happy, but occasionally it can lead to code obfuscation. So before you go galumphing back to your project, take a few minutes and follow these suggestions to keep your code readable, and avoid those Jabberwocky methods:

  • Using modules is a self-documenting way to extend the functionality of your classes. If you do decide to use a shared library to cover some functionality, try to use modules rather than re-opening classes.

  • Be very careful when you use metaprogramming techniques like method_missing, or dynamic code creation. Writing a lot of crafty methods using a few lines of Ruby can be lots of fun, but sometimes a little bit of duplication can improve the readability of your code tenfold.

  • Lastly, documentation and tidy code is important. Try to organize your methods, and definitely drop a comment into the class if you know a shared library will be mutating it down the road.

Be sure to keep these tips in mind, and you'll find whoever inherits the code after you will chortle in his joy.

Categories
Author

In Blackberry Java application development, every row in ListField has the default blue focus highlight color. There is no simple setter to change it. One way to change it is to overwrite the 'drawFocus' method. I'm going to walk you through the steps to change that.

Suppose we have a list to display each news feed from an RSS; we need to customize the row so that it looks like this:

In the non-focus state, the title of the news feed is in black, the date info is in gray, and the background color for the row is white. For the focus state the colors will be changed: the row gets a red highlight color and the title/date fields will get white. Here is the code:

protected void drawFocus(Graphics graphics, boolean on) {     //get the focus rect area     XYRect focusRect = new XYRect();     getFocusRect(focusRect);      boolean oldDrawStyleFocus = graphics.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS);     try {         if (on) {            //set the style so the fields in the row will update its color accordingly             graphics.setDrawingStyle(Graphics.DRAWSTYLE_FOCUS, true);             int oldColour = graphics.getColor();             try {                 graphics.setColor(Color.RED); //set the color and draw the color                 graphics.fillRect(focusRect.x, focusRect.y,                                   focusRect.width, focusRect.height);             } finally {                 graphics.setColor(oldColour);             }             //to draw the row again             drawListRow(this, graphics, getSelectedIndex(),                         focusRect.y, focusRect.width);         }      } finally {       graphics.setDrawingStyle(Graphics.DRAWSTYLE_FOCUS, oldDrawStyleFocus);     } } 

The idea is to draw the customized highlight color and then draw the selected row again. The drawListRow method will draw each row; suppose we have the title field’s paint method like this:

protected void paint(Graphics g) {     try {         g.setColor(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS)                    ? textFocusColor : textUnFocusColor);         g.drawText(__line1, PADDING_LEFT, PADDING_TOP);          if (__line2 != null) {             g.setDrawingStyle(DrawStyle.ELLIPSIS, true);             g.drawText(__line2, PADDING_LEFT, PADDING_TOP + _font.getHeight());         }     } finally {         if (__line2 != null) {             g.setDrawingStyle(DrawStyle.ELLIPSIS, false);         }     } } 

Here the title takes 2 lines at most. And the paint method will be invoked by its manager from the drawListRow method. Check back for more Blackberry tips on our blog in the future!

Categories
Author
Subscribe to Tips