<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Cory Schires</title>
	<atom:link href="http://coryschires.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://coryschires.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Tue, 14 Feb 2012 22:45:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Ten tips for writing better Cucumber steps</title>
		<link>http://coryschires.com/ten-tips-for-writing-better-cucumber-steps/</link>
		<comments>http://coryschires.com/ten-tips-for-writing-better-cucumber-steps/#comments</comments>
		<pubDate>Sun, 01 Jan 2012 23:08:19 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[Best-Practices]]></category>
		<category><![CDATA[Capybara]]></category>
		<category><![CDATA[Cucumber]]></category>
		<category><![CDATA[Ruby-on-Rails]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=420</guid>
		<description><![CDATA[I've written hundreds of Cucumber steps. Here's some tips I learned along the way.]]></description>
			<content:encoded><![CDATA[<h3>1. Use flexible pluralization.</h3>
<p>Add a <span class="code_text">?</span> immediately following the pluralized word:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^the users? should receive an email$/ do
          # ...
        end
    </pre>
</div>
<p>The <span class="code_text">?</span> specifies that your looking for zero or more of the proceeding character. So the above example will capture both <span class="code_text">user</span> and <span class="code_text">users</span>.</p>
<h3>2. Use non-capturing groups to help steps read naturally.</h3>
<p>You can create non-capturing groups by adding a <span class="code_text">?:</span> to the beginning of a otherwise normal group (e.g. <span class="code_text">(?:some text)</span> rather than <span class="code_text">(some text)</span>). This is treated exactly like a normal group except that the result will is not captured and thus not passed as an argument to your step definition. This often useful in conjunction with alternation:</p>
<div class="code_block">
<pre class="brush: ruby;">
        And /^once the files? (?:have|has) finished processing$/ do
          # ...
        end
    </pre>
</div>
<p>Or another pattern I use regularly:</p>
<div class="code_block">
<pre class="brush: ruby;">
        When /^(?:I|they) create a profile$/ do
          # ...
        end
    </pre>
</div>
<h3>3. Consolidate step definitions by capturing optional groups.</h3>
<p>Often I find myself writing essentially the same step with both positive and negative assertions. You can remove this duplication by capturing an optional group:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^I should( not)? see the following columns: "([^"]*)"$/ do |negate, columns|
          within('table thead tr') do
            columns.split(', ').each do |column|
              negate ? page.should_not(have_content(column)) : page.should(have_content(column))
            end
          end
        end
    </pre>
</div>
<p>Here we&#8217;re capturing an optional group (note <span class="code_text">( not)?</span> using the <span class="code_text">?</span> mentioned above). We then pass that into our step as the <span class="code_text">negate</span> variable which we can use to write conditional assertions.</p>
<h3>4. Not all matched phrases need to be surrounded by quotes.</h3>
<p>Don&#8217;t assume that matched phrases must (or should) be enclosed in double quotes. Often quotes are a good idea. They make it visually clear which phrases will be passed to the step definition. For example:</p>
<div class="code_block">
<pre class="brush: plain;">
        Given I have "potatoes" in my cart
    </pre>
</div>
<p>That&#8217;s reasonable. The quotes highlight the parts that change without hurting readability. But sometimes, quotes are just poor style:</p>
<div class="code_block">
<pre class="brush: plain;">
        Given I have "7" items in my cart
    </pre>
</div>
<p>It should be pretty obvious that the number is variable. The quotes add nothing except noise. A better step would read:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^I have (\d+) items? in my cart$/ do |item_count|
          item_count.to_i.times { ... }
        end
    </pre>
</div>
<h3>5. Use transforms to make smarter, DRYer regular expressions.</h3>
<p>There&#8217;s an opportunity to refactor the previous example. Do you see it? Cucumber passes everything as a string, so you must remember to convert types within your step definition (e.g. above we use <span class="code_text">to_i</span> to transform <span class="code_text">item_count</span> into a proper integer). That&#8217;s annoying and easy to forget.</p>
<p>Fortunately, Cucumber gives us a way to avoid this peskiness by using <span class="code_text">Transform</span>:</p>
<div class="code_block">
<pre class="brush: ruby;">
        CAPTURE_A_NUMBER = Transform /^\d+$/ do |number|
          number.to_i
        end
    </pre>
</div>
<p>And we can use this in our steps:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^I have (#{CAPTURE_A_NUMBER}) items? in my cart$/ do |item_count|
          item_count.times { ... }
        end
    </pre>
</div>
<p>Not only have we removed the need to call <span class="code_text">to_i</span> but we&#8217;ve also moved our regex into a reusable constant.</p>
<h3>6. Define methods to DRY up your step definitions.</h3>
<p>Sometimes it&#8217;s a good idea to remove duplication by defining methods. For example, it&#8217;s common to define a <span class="code_text">current_user</span> method:</p>
<div class="code_block">
<pre class="brush: ruby;">
        def current_user
          User.find_by_email('current_user@example.com')
        end
    </pre>
</div>
<p>Similarly, if you find yourself wrapping several steps with the same logic, you might consider making a helper method. On <a href="http://scholasticahq.com/">Scholastica</a>, we test a lot of lightboxes using of this method:</p>
<div class="code_block">
<pre class="brush: ruby;">
        def within_lightbox(opts = {sleep: 0} )
          sleep(opts[:sleep])
          within_frame("prettyPhotoIframe") { yield }
        end
    </pre>
</div>
<p>And our step definitions stay nice and clean:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^some stuff should be visible in the lightbox$/ do
          within_lightbox { page.should have_content('Some Stuff') }
        end
    </pre>
</div>
<p>By convention, these methods should live in <span class="code_text">features/support/world_extensions.rb</span> and be included in the Cucumber <span class="code_text">World</span> module. But keep in mind this is a tradeoff: you&#8217;re removing duplication but adding indirection. You should be reluctant to define methods until the code makes it very obvious that it&#8217;s a good idea.</p>
<h3>7. Use steps within steps.</h3>
<p>Sometimes it&#8217;s useful to call steps within steps. Another example from <a href="scholasticahq.com">Scholastica</a>:</p>
<div class="code_block">
<pre class="brush: ruby;">
        When /^the request for an expedited decision should be canceled$/ do
          manuscript.should_not be_expedited
          step %{"#{current_user.email}" should receive an email with subject "Expedited decision request canceled"}
        end
    </pre>
</div>
<p>But don&#8217;t go crazy, it&#8217;s better to use the capybara methods directly when possible:</p>
<div class="code_block">
<pre class="brush: ruby;">
        When /^I update the email template to read "([^"]*)"$/ do |text|
          fill_in("email_template[text], with: text)
          click_button("Save changes and close")
          # Rather than...
          # step %{I fill in "email_template[text]" with "#{text}"}
          # step %{I press "Save changes and close"}
        end
    </pre>
</div>
<h3>8. Improve readability with unanchored regular expressions.</h3>
<p>Most step definitions look something like:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Given /^I am an admin user$/ do |item_count|
          # ...
        end
    </pre>
</div>
<p>Note we&#8217;re using <span class="code_text">^</span> and <span class="code_text">$</span> to anchor our regex to the start and end of the captured string. This ensures the regular expression exactly matches &#8220;I am an admin user&#8221; (i.e. allows no additional words at the beginning or end of the step). Most of the time, this is exactly what want.</p>
<p>Occasionally, however, it makes sense to omit the final <span class="code_text">$</span>. Take this step for example:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^wait (\d+) seconds/ do |seconds|
          sleep(seconds.to_i)
        end
    </pre>
</div>
<p>Now you can use this definition to write flexible, expressive steps:</p>
<div class="code_block">
<pre class="brush: plain;">
        Then wait 2 seconds for the revenue statistics to finish loading
        Then wait 5 seconds while the document is converted
    </pre>
</div>
<h3>9. When your steps must include data, use tables.</h3>
<p>Generally, steps should be human readable and that means they shouldn&#8217;t include loads of cryptic data. But sometimes, you have no other choice. In those cases, use tables to clearly represent the data:</p>
<div class="code_block">
<pre class="brush: plain;">
        Given "Frankie's Hams" are selling for $25:
        And the following orders have been placed:
          | buyer email      | quantity |
          | eddy@example.com | 3        |
          | matt@example.com | 2        |
    </pre>
</div>
<p>Using tables within your step definitions can get a bit tricky. I use <a href="https://gist.github.com/1548498">this helper method</a> but you should really <a href="https://github.com/cucumber/cucumber/blob/master/lib/cucumber/ast/table.rb">read the relevant source code</a> and figure out what makes sense for your application.</p>
<h3>10. Don&#8217;t get carried away and spoil a good thing.</h3>
<p>As you use these tips, remember that tests should favor clarity over cleverness. In other words, if you&#8217;re removing a small amount of duplication but adding a lot of complexity, that&#8217;s a poor tradeoff. Here&#8217;s an example from <a href="scholasticahq.com">Scholastica</a>:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Given /^(?:I|they) have opened (?:a|an) ([^\s]+) invitation$/ do |invitation_type|
          invitation = Factory("#{invitation_type}_invitation".to_sym, recipient: current_user, to: current_user.email)
          reset_mailer
          eval "ApplicationMailer.invite_#{invitation_type}(invitation).deliver"
          open_email(current_user.email)
        end
    </pre>
</div>
<p>This steps allows us to write both <span class="code_text">Given I have opened a reviewer invitation</span> and <span class="code_text">Given I have opened an editor invitation</span>. I&#8217;d say this step is borderline too complex (lots of interpolation and an eval). Maybe it would be better to just write two separate steps? Remember no one is testing your tests so don&#8217;t fuck around. A little bit of duplication is not the end of the world.</p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/ten-tips-for-writing-better-cucumber-steps/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Moving your application to Heroku</title>
		<link>http://coryschires.com/moving-your-application-to-heroku/</link>
		<comments>http://coryschires.com/moving-your-application-to-heroku/#comments</comments>
		<pubDate>Tue, 20 Sep 2011 19:11:27 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[amazon-rds]]></category>
		<category><![CDATA[heroku]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[postgres]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=415</guid>
		<description><![CDATA[Some tips on moving your application to Heroku. Also, a script to help remove bad encoding from you database.]]></description>
			<content:encoded><![CDATA[<p>Recently, I moved an app from Rack Space to Heroku. Everything went well except for a few hangups.</p>
<h3>Migrating your database.</h3>
<p>My app currently used MySQL and, as you probably know, Heroku love Postgres. So how do we get this data up to Heroku?</p>
<p>One option would be to use the <a href="http://devcenter.heroku.com/articles/taps">taps gem</a> to import the MySQL data into Postgres. But that didn&#8217;t work so well for me. The gem seemed to fail arbitrarily, leaving me unsure about the fidelity of my data.</p>
<p>Another option, use Heroku&#8217;s <a href="http://devcenter.heroku.com/articles/amazon_rds">Amazon RDS addon</a>. It was a little painful to setup but not terrible and there&#8217;s plenty of <a href="http://aws.amazon.com/rds/">good documentation</a>.</p>
<h3>Fixing bad encodings.</h3>
<p>Once I got my database migrated, I noticed a new issue. Little  �&#8217;s were peppered throughout my copy. That&#8217;s a bad encoding since, apparently, I&#8217;m using a different version of MySQL. So I wrote a little script to replace bad encodings with <a href="http://www.w3schools.com/tags/ref_entities.asp">HTML entities</a>.</p>
<p><script src="https://gist.github.com/1230008.js"> </script></p>
<p>It&#8217;s not exhaustive, but it&#8217;s solid and should be easy to adapt if needed.</p>
<h3>Things to watch out for.</h3>
<ul>
<li>Does your app use SSL? If so, plan ahead since that can take a few days to work out.</li>
<li>If you&#8217;re using sendgrid, be sure to choose a plan that won&#8217;t cap out and start throwing errors.</li>
<li>Don&#8217;t forget to set both your <span class="code_text">MX</span> and <span class="code_text">A</span> records.</li>
<li>Don&#8217;t forget to setup New Relic and Hoptoad before switching over. You&#8217;ll probably encounter some errors and it&#8217;s better to know about them.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/moving-your-application-to-heroku/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding default configuration options to Paperclip</title>
		<link>http://coryschires.com/add-default-configuration-options-to-paperclip/</link>
		<comments>http://coryschires.com/add-default-configuration-options-to-paperclip/#comments</comments>
		<pubDate>Sun, 24 Jul 2011 00:02:40 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[paperclip]]></category>
		<category><![CDATA[Ruby-on-Rails]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=408</guid>
		<description><![CDATA[DRY up your paperclip'd models by making a paperclip_defaults initializer.]]></description>
			<content:encoded><![CDATA[<p>Using paperclip, you&#8217;ll often put something like this in your models:</p>
<div class="code_block">
<pre class="brush: ruby;">
      has_attached_file :article_text,
        :storage => :s3,
        :s3_credentials => {
          :bucket => ENV['AS3_BUCKET'],
          :access_key_id => ENV['AS3_ACCESS_KEY_ID'],
          :secret_access_key => ENV['AS3_SECRET_ACCESS_KEY']
        }
       :s3_permissions => :private,
       :processors => [:manuscript_converter],
       :path => "manuscript/:id/:uploaded_manuscript_filename"
    </pre>
</div>
<p>Many of these settings will be repeated in every paperclip&#8217;d model. You can easily remove that duplication by adding an initializer. In <span class="code_text">config/initializers/paperclip_defaults.rb</span>:</p>
<div class="code_block">
<pre class="brush: ruby;">
      Paperclip::Attachment.default_options.merge!(
        :storage => :s3,
        :s3_credentials => {
          :bucket => ENV['AS3_BUCKET'],
          :access_key_id => ENV['AS3_ACCESS_KEY_ID'],
          :secret_access_key => ENV['AS3_SECRET_ACCESS_KEY']
        }
      )
    </pre>
</div>
<p>And now you can remove those options from all your models – separating the parts that change from the parts that stay the same.</p>
<p>I had trouble finding this online and had to dig through the source code to figure it out. So maybe it will help someone else save a little time.</p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/add-default-configuration-options-to-paperclip/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Maintaining a reading list on GitHub</title>
		<link>http://coryschires.com/maintaining-a-reading-list-on-github/</link>
		<comments>http://coryschires.com/maintaining-a-reading-list-on-github/#comments</comments>
		<pubDate>Mon, 21 Feb 2011 21:45:16 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Best-Practices]]></category>
		<category><![CDATA[GitHub]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=382</guid>
		<description><![CDATA[Recently I took the time to post a reading list to GitHub. I've found some surprising benefits...]]></description>
			<content:encoded><![CDATA[<p>Like any decent programmer, I spend a lot of time reading. For the most part it runs in cycles: read a bunch of stuff, apply what you&#8217;ve learned, read a bunch more, and so on. This is a pretty typical pattern as becoming a strong developer requires a good mix of learning and doing. So, inspired in part by <a href="http://oreilly.com/catalog/9780596518387" class="new_window">Apprenticeship Patterns</a>, I&#8217;ve decided to start maintaining a reading list.</p>
<p><img class="blog_post_banner" src="http://coryschires-blog-post-images.s3.amazonaws.com/reading-list.png" alt="Screenshot of reading list"></p>
<h3>Some simple ground rules for myself.</h3>
<ul>
<li>List should be <a href="https://github.com/coryschires/reading-list" class="new_window">publicly available on github</a>.</li>
<li>Be honest about what books I’ve read, partially read, and plan to read.</li>
<li>Write a few sentences about each book &ndash; mostly for myself but also for anyone who might be interested.</li>
<li>Only include books related to development, user experience design, and entrepreneurship.</li>
<li>Include screencasts as well since that’s how I do much of my learning.</li>
</ul>
<h3>I&#8217;ve already noticed some benefits.</h3>
<p>Although it&#8217;s only been a short time, I can already attest to the usefulness of keeping track of what you&#8217;ve read. Just building the list requires going back through all the stuff you&#8217;ve read and watched over the past few years. It&#8217;ll get you thinking about how you learn, including some really interesting questions:</p>
<ul>
<li>How have your interests moved between topics?</li>
<li>What topics do you keep coming back to?</li>
<li>What periods were most productive?</li>
<li>What topics required a few books before you really understood?</li>
<li>What type of books are most useful for the way you learn? (e.g. Do you learn better with lots of examples or would you rather read a short book twice?)</li>
<li>Were any of the books disappointing? Why?</li>
</ul>
<p>I think it&#8217;s important that your list be more than a catalogue of titles and author names. You should take the time to reflect on why the book mattered (i.e. what did you take away from the read?). While this means writing a few sentences for each entry, don&#8217;t get too fixated. There&#8217;s no reason to write a summary or book review. The writeup is just to get you thinking broadly about the book.</p>
<h3>And you should do it too.</h3>
<p>Finally, I&#8217;d like to see other developers maintaining a reading list &ndash; specifically on GitHub. It&#8217;d be awesome if I could look up serious developers to check out what they&#8217;re reading and, more importantly, what they recommend. It&#8217;d be a nice adjunct to reading their code.</p>
<p><a href="https://github.com/coryschires/reading-list" class="download">View my reading list on Github</a></p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/maintaining-a-reading-list-on-github/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>jQuery Splatter Plugin</title>
		<link>http://coryschires.com/jquery-splatter-plugin/</link>
		<comments>http://coryschires.com/jquery-splatter-plugin/#comments</comments>
		<pubDate>Wed, 09 Feb 2011 21:42:30 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=373</guid>
		<description><![CDATA[Splatter is a jQuery plugin which applies a random position, size, and color to elements on a page.]]></description>
			<content:encoded><![CDATA[<p>Splatter is a jQuery plugin which applies a random position, size, and color to elements on a page. The most basic implementation adds randomly colored and positioned asterisks to the element:</p>
<p><img class="blog_post_banner" src="http://coryschires-blog-post-images.s3.amazonaws.com/splatter/basic_splatter.jpg" alt="simple_example"></p>
<p>To see some working examples, check out the <a href="http://coryschires.github.com/splatter/" class="new_window">demo page</a>.</p>
<h3>Basic usage.</h3>
<p>Add these scripts in the <span class="code_text">head</span> element of your page:</p>
<div class="code_block">
<pre class="brush: ruby">
        &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt;
        &lt;script src="jquery.splatter.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt;
    </pre>
</div>
<p>Invoke the plugin, specifying configuration options as needed. For example, pass an array of <span class="code_text">splats</span> if you&#8217;d like to use words rather than asterisks:</p>
<div class="code_block">
<pre class="brush: jscript">
        $('#word_splatter').splatter({
          min_font_size: 20,
          max_font_size: 50,
          splats: ["Lorem", "Ipsum", "Dolor", "Sit", "Amet", "Consectetur", "Adipisicing", "Elit", "Sed", "Do", "Eiusmod", "Tempor", "Incididunt", "Ut", "Labore", "Et", "Dolore", "Magna", "Aliqua", "Ut", "Enim", "Ad", "Minim", "Veniam", "Quis", "Nostrud", "Exercitation", "Ullamco", "Laboris", "Nisi", "Ut", "Aliquip", "Ex", "Ea", "Commodo", "Consequat"]
        });
    </pre>
</div>
<p>Which creates:</p>
<p><img class="blog_post_banner" src="http://coryschires-blog-post-images.s3.amazonaws.com/splatter/word_splatter.jpg" alt="Splatter example using words"></p>
<h3>Configuration options.</h3>
<p>Splatter has lots of configuration options but most of them are pretty simple and none of them are required:</p>
<div class="code_block">
<pre class="brush: jscript">
        $('#splatter_box').splatter({
          custom_attributes: [],      // specify custom attributes to add to splats which can be used to store data
          colors: [],                 // specify the colors to be randomly applied to the splats
          splats: [],                 // specify strings to be used as splats – defaults to *
          hover_on: function() {},    // add a custom function to be called when hovering on a splat
          hover_off: function() {},   // add a custom function to be called when hovering off a splat
          splat_count: 20,            // number of splats that will be drawn
          min_font_size: 20,          // minimum font size for splats
          max_font_size: 300,         // maximum font size for splats
          height: $(window).height(), // height of splatter
          width: $(window).width()    // width of splatter
        });
    </pre>
</div>
<p>Most of these should be fairly obvious but let&#8217;s go into a bit more detail on how to use custom attributes. Custom attributes allow you to apply data attributes with random values to each splat. They are specified as an array of objects:</p>
<div class="code_block">
<pre class="brush: jscript">
        $('#splatter_box').splatter({
          custom_attributes: [
            { name: "data-hover_color", values: ['#f68a00', '#069', '#a70'] },
            { name: "data-slide_position", values: ['20', '50', '100'] }
          ]
        });
    </pre>
</div>
<p>Each custom attribute object should have two keys: a <span class="code_text">name</span> and <span class="code_text">values</span>. The <span class="code_text">name</span> will be used as the attribute&#8217;s name. The <span class="code_text">values</span> key takes an array of possible values. The actual value for any given custom attribute is randomly selected from the <span class="code_text">values</span> array.</p>
<p>So the the above example might create splats that look like:</p>
<div class="code_block">
<pre class="brush: ruby">
        <span class="splat" data-slide_position="20" data-hover_color="#f68a00">*</span>
        <span class="splat" data-slide_position="100" data-hover_color="#069">*</span>
    </pre>
</div>
<p>Often custom attributes work in conjunction with custom hover events, allowing you to use jQuery to fetch these custom values and do something interesting (e.g. fade in a different color, animate a splats position, or make a splat randomly rotate). For example, let&#8217;s create 100 splats in shades of gray that fade into random colors on hover:</p>
<div class="code_block">
<pre class="brush: jscript">
        $('#animated_colors').splatter({
          width: 700,
          height: 250,
          splat_count: 100,
          colors: ['#ccc', '#e0e0e0', '#333', '#666', '#999'],
          custom_attributes: [
            { name: "data-hover_color", values: ['#f68a00', '#069', '#a70', '#090', '#ff1493', '#0066CC', '#ff1493', '#F0E356'] }
          ],
          hover_on: function(splat) {
            var original_color = splat.css('color');
            var hover_color = splat.attr('data-hover_color')
            splat.css('color', hover_color).attr('data-hover_color', original_color);
          },
          hover_off: function(splat) {
            var original_color = splat.css('color');
            var hover_color = splat.attr('data-hover_color');
            splat.css('color', hover_color).attr('data-hover_color', original_color);
          }
        });
    </pre>
</div>
<p>And add some CSS3 to handle the color transitions:</p>
<div class="code_block">
<pre class="brush: css">
        .splatter_box .splat {
          transition: color 0.5s linear;
          -moz-transition: color 0.5s linear;
          -o-transition: color 0.5s linear;
          -webkit-transition: color 0.5s linear;
          cursor: pointer;
        }
    </pre>
</div>
<p>Which will create something like:</p>
<p><img class="blog_post_banner" src="http://coryschires-blog-post-images.s3.amazonaws.com/splatter/hover_splatter.jpg" alt="Example with color transitions"></p>
<p>If you need additional help understanding the various configuration options, check out the <a href="http://coryschires.github.com/splatter/" class="new_window">live demos</a> as well as the <a href="https://github.com/coryschires/splatter/blob/master/spec/splatter_spec.js" class="new_window">unit tests</a>.</p>
<p><a class="download new_window" href="https://github.com/coryschires/splatter">Download the project from GitHub</a> </p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/jquery-splatter-plugin/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Making Breakout with Processing.js.</title>
		<link>http://coryschires.com/breakout-clone-in-processing-js/</link>
		<comments>http://coryschires.com/breakout-clone-in-processing-js/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 20:23:41 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=349</guid>
		<description><![CDATA[As few months back, I spent the weekend reverse engineering breakout with Processing.js. Checkout the <a href="https://github.com/coryschires/breakout-clone">source code</a>.]]></description>
			<content:encoded><![CDATA[<p>As few months back, I spent the weekend reverse engineering <a href="https://github.com/coryschires/breakout-clone">breakout with Processing.js</a>. If you haven&#8217;t had a chance to spend some time with this language, you really should. Processing is an easy-to-learn, open-source programming language for making images, animation, and interactions. </p>
<p>Click the image below to <a href="http://coryschires.github.com/breakout-clone/" class="new_window">play the demo</a>. Control paddle using your  mouse.</p>
<p><a class="no_underline new_window" href="http://coryschires.github.com/breakout-clone/"><br />
     <img class="msg" title="Click to play demo." src="http://coryschires-blog-post-images.s3.amazonaws.com/breakout_screenshot.png" alt="Breakout Screenshot"><br />
</a></p>
<div class="clear"></div>
<p>Here&#8217;s a high level overview of the code. Like any processing script, we start by initializing some variables:</p>
<div class="code_block">
<pre class="brush: java;">
      // --- colors ---
      color black = color(0);
      color bright_green = color(110,212,111);
      color pink = color(190,81,163);
      color purple = color(97,81,190);
      color light_blue = color(142, 185,234);
      color yellow = color(212,197,110);

      // --- initialize arrays for bricks ---
      Brick[] pink_bricks = new Brick[10];
      Brick[] green_bricks = new Brick[10];
      Brick[] navy_bricks = new Brick[10];
      Brick[] blue_bricks = new Brick[10];
      Brick[] yellow_bricks = new Brick[10];
      array[] bricks = new array[5];
    </pre>
</div>
<p>Then we do some configuration in our <span class="code_text">setup</span> block:</p>
<div class="code_block">
<pre class="brush: java;">
      void setup() {
       size(400,400);
       frameRate(80);

       // initialize game, paddle, ball
       game = new Game();
       paddle = new Paddle();
       ball = new Ball(200, 375);

       // initialize bricks
       for (int a=0; a<10; a++) {
           pink_bricks[a] = new Brick(a*40, 0, pink);
           green_bricks[a] = new Brick(a*40, 20, bright_green);
           navy_bricks[a] = new Brick(a*40, 40, purple);
           blue_bricks[a] = new Brick(a*40, 60, light_blue);
           yellow_bricks[a] = new Brick(a*40, 80, yellow);
       }

       // combine all bricks into single array of arrays
       bricks[0] = pink_bricks;
       bricks[1] = green_bricks;
       bricks[2] = navy_bricks;
       bricks[3] = blue_bricks;
       bricks[4] = yellow_bricks;
      }
</pre>
</div>
<p>Then we have a draw loop. This is an endless loop where we can place our game logic:</p>
<div class="code_block">
<pre class="brush: java;">
      void draw() {
       background(black);

       // draw bricks
       game.build(bricks);

       // draw paddle and ball
       paddle.display(mouseX);
       ball.display(); 

       // animate ball
       if (game.active) {
           ball.move();
       } else {
           ball.rest_on_paddle(paddle);
           game.reset(bricks);
           $('#messages #start').show();
       }

       // if ball goes off screen
       if ( ball.off_screen() ) {
           game.active = false;
       }

       // if ball hit paddle
       if ( ball.hit_paddle(paddle) ) {
           ball.rebound_off(paddle);
       }

       // if ball hits bricks
       if (ball_y <= 100) {
           hit_brick = game.determine_colision(ball, bricks);

           if (hit_brick.is_active()) {
               hit_brick.deactivate();
               ball.bounce_off_brick(hit_brick);
               game.increment_points(10);
           }
       }
      }
    </pre>
</div>
<p>Finally we have a simple <span class="code_text">keyPressed</span> function to allow the user to pause the game.</p>
<div class="code_block">
<pre class="brush: java;">
      void keyPressed() {
       // when user presses space bar
       if (key == 64) {
           if ( ball.is_in_start_position() ) {
               ball.move_upward(); // start game
               game.active = true;
               $('#messages #start').hide();
           } else {
               ball.toggle_pause(); // pause/resume game
           }
       }
      }
    </pre>
</div>
<p>From here on out, it's pretty simple. Everything is object oriented in a sensible manner. First, we have a <span class="code_text">game</span> class. This holds all the application wide functionality as well as things that generally don't fit well into other classes but also don't merit a separate class (e.g. points):</p>
<div class="code_block">
<pre class="brush: java;">
      class Game {
       int points;
       int level;
       boolean active;

       Game() {
           points = 0;
           level = 1;
           active = false;
       }

       void build(bricks) {
           for (int i=0; i < bricks.length; i++) {
               for (int x=0; x < bricks[i].length; x++) {
                   bricks[i][x].display();
               }
           }
       }

       void reset(bricks) {
           for (int i=0; i < bricks.length; i++) {
               for(int x=0; x < bricks[i].length; x++) {
                   brick = bricks[i][x];
                   brick.brick_active = true;
                   brick.brick_color = brick.original_color;
               }
           }
       }

       void increment_points(points_earned) {
           points += points_earned;
           $('#game_stats #points span').html(points);
       }

       void determine_colision(ball, bricks) {
           y = ball.show_ball_y();
           x = ball.show_ball_x();     

           // find brick row based on ball location
           if      (y >= 0 &#038;&#038; y <=  20) { row = 0; }
           else if (y > 20 &#038;&#038; y <=  40) { row = 1; }
           else if (y > 40 &#038;&#038; y <=  60) { row = 2; }
           else if (y > 60 &#038;&#038; y <=  80) { row = 3; }
           else if (y > 80 &#038;&#038; y <= 100) { row = 4; }

           // find brick column based on ball location
           if      (x >=  0 &#038;&#038; x <=  40) { col = 0; }
           else if (x >  40 &#038;&#038; x <=  80) { col = 1; }
           else if (x >  80 &#038;&#038; x <= 120) { col = 2; }
           else if (x > 120 &#038;&#038; x <= 160) { col = 3; }
           else if (x > 160 &#038;&#038; x <= 200) { col = 4; }
           else if (x > 200 &#038;&#038; x <= 240) { col = 5; }
           else if (x > 240 &#038;&#038; x <= 280) { col = 6; }
           else if (x > 280 &#038;&#038; x <= 320) { col = 7; }
           else if (x > 320 &#038;&#038; x <= 360) { col = 8; }
           else if (x > 360 &#038;&#038; x <= 400) { col = 9; }

           return bricks[row][col];
       }
      }
    </pre>
</div>
<p>Next, we have a ball class...</p>
<div class="code_block">
<pre class="brush: java;">
      class Ball {

       Ball(temp_ball_x, temp_ball_y) {
           ball_diameter = 10;
           ball_x = temp_ball_x;
           ball_y = temp_ball_y;
           speed_x = 0;
           speed_y = 0;
           speed_max = 4;
           pre_pause_speed  = [0,0];
       }

       void display() {
           noStroke();
           fill(bright_green);
           ellipse(ball_x, ball_y, ball_diameter, ball_diameter);
       }

       void move() {
           // make ball bounce off ceiling
           if (ball.edge("top") < 0) {
               speed_y = speed_y * -1;
           }
           // make ball bounce off either sidewall
           if ( ball.edge("left") < 0 || ball.edge("right") > width ) {
               speed_x = speed_x * -1;
           }
           // animate ball
           ball_x += speed_x;
           ball_y += speed_y;
       }

       void toggle_pause() {
           if (speed_x == 0 &#038;&#038; speed_y == 0) {
               speed_x = pre_pause_speed[0];
               speed_y = pre_pause_speed[1];
               $('#messages #pause').hide();
           } else {
               pre_pause_speed[0] = speed_x;
               pre_pause_speed[1] = speed_y;
               speed_x = 0;
               speed_y = 0;
               $('#messages #pause').show();
           }
       }

       void rest_on_paddle(paddle) {
           // stop ball from moving
           speed_x = 0;
           speed_y = 0;
           // constrain resting position to keep ball on center of paddle
           resting_position = constrain(mouseX, paddle.half_width(), width - paddle.half_width());
           // place ball atop paddle
           ball_y = 375;
           ball_x = resting_position;
       }

       void is_in_start_position() {
           if ( ball_y == 375 &#038;&#038; (speed_y == 0 &#038;&#038; speed_x == 0) ) {
               return true;
           } else {
               return false;
           }
       }

       void move_upward() {
           speed_x = 0;
           speed_y = -3;
       }

       void bounce_off_brick(brick) {
           bcp = brick.center_point();
           distance_at_bounce = dist(bcp[0],bcp[1], ball_x,ball_y);

           if (distance_at_bounce >= 20) {
               speed_x = speed_x * -1;
           } else {
               speed_y = speed_y * -1;
           }
       }

       void edge(edge) {
           if (edge == "top") {
               ball_edge = ball_y - 5;
           } else if (edge == "bottom") {
               ball_edge = ball_y + 5;
           } else if (edge == "left") {
               ball_edge = ball_x - 5;
           } else if (edge == "right") {
               ball_edge = ball_x + 5;
           } else {
               return console.log("Argument Error - Valid arguements: top, bottom, left, right");
           }
           return ball_edge;
       }

       void off_screen() {
           if (ball_y > height) {return true;} else {return false;}
       }

       void hit_paddle(paddle) {
           if (ball_y > paddle.edge("top") &#038;&#038; (ball_x > paddle.edge("left") &#038;&#038; ball_x < paddle.edge("right") )) {
               return true;
           } else {
               return false;
           }
       }

       void rebound_off(paddle) {
           // cacluate distance between point of contact and center of paddle
           bounce_point = dist(
               ball_x, paddle.show_paddle_y(), // point of contact
               paddle.show_paddle_x(), paddle.show_paddle_y() // center of paddle
           );

           // calculate rebound angle relative to bounce point
           if (ball_x < paddle.show_paddle_x()) {
               speed_x = (bounce_point * 0.05) * -1;
           } else {
               speed_x = bounce_point * 0.05;
           }

           // calculate y speed relative to rebound angle
           speed_y = (speed_max - abs(speed_x)) * -1;
       }

       void show_ball_x() {
           return ball_x;
       }

       void show_ball_y() {
           return ball_y;
       }

      }
    </pre>
</div>
<p>Then a brick class...</p>
<div class="code_block">
<pre class="brush: java;">
       color brick_stroke;
       color brick_color;
       color original_color;
       int brick_width;
       int brick_height;
       int brick_x;
       int brick_y;
       boolean brick_active;   

       Brick(temp_brick_x, temp_brick_y, temp_color) {
           brick_stroke = black;
           brick_color = temp_color;
           brick_width = 40;
           brick_height = 20;
           brick_x = temp_brick_x;
           brick_y = temp_brick_y;
           brick_active = true;
           original_color = temp_color;
       }

       void display() {
           rectMode(CORNER);
           stroke(brick_stroke);
           fill(brick_color);
           rect(brick_x, brick_y, brick_width, brick_height);
       }

       void is_active() {
           return brick_active;
       }

       void deactivate() {
           brick_active = false;
           brick_color = black;
       }

       void center_point() {
           return [brick_x + brick_width/2, brick_y + brick_height/2 ];
       }
      }
    </pre>
</div>
<p>Finally, a paddle class...</p>
<div class="code_block">
<pre class="brush: java;">
      class Paddle {
       int paddle_width;
       int paddle_height;
       color paddle_color;
       float paddle_x;
       float paddle_y;

       Paddle() {
           paddle_width = 80;
           paddle_height = 7;
           paddle_color = bright_green;
           paddle_x = width/2;
           paddle_y = 385;
       }

       void display() {
           // determine paddle_y and constrain so paddle cannot leave screen
           paddle_x = constrain(mouseX, paddle_width/2, width - paddle_width/2);

           // draw paddle
           rectMode(CENTER);
           noStroke();
           fill(paddle_color);
           rect(paddle_x, paddle_y, paddle_width, paddle_height);
       }

       void edge(edge) {
           if (edge == "left") {
               return paddle_x - (paddle_width/2);
           } else if (edge == "right") {
               return paddle_x + (paddle_width/2);
           } else if (edge == "top") {
               return paddle_y -5;
           } else {
               return console.log("Argument Error - Valid arguements: left, right, top");
           }
       }

       void half_width() {
           return paddle_width/2;
       }

       void show_paddle_x() {
           return paddle_x;
       }

       void show_paddle_y() {
           return paddle_y;
       }
      }
    </pre>
</div>
<p><a href="https://github.com/coryschires/breakout-clone" class="new_window download">Download the project from Github</a></p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/breakout-clone-in-processing-js/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Dynamic CSS3 Buttons with LESS</title>
		<link>http://coryschires.com/dynamic-css3-buttons-with-less/</link>
		<comments>http://coryschires.com/dynamic-css3-buttons-with-less/#comments</comments>
		<pubDate>Sun, 04 Jul 2010 20:03:39 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[LESS]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=334</guid>
		<description><![CDATA[Lean how to make your buttons dynamic using LESS - an awesome new CSS abstraction language.]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s been a lot of buzz surrounding CSS3 buttons &#8211; including some <a href="http://www.webdesignerwall.com/tutorials/css3-gradient-buttons/">really great tutorials</a>. The concept behind a basic button, however, is pretty simple:</p>
<ol class="block_list">
<li>Apply a subtle background gradient</li>
<li>Add some rounded corners</li>
<li>Add text shadows &#8211; optionally</li>
<li>Add a thin border &#8211; optionally</li>
<li>Add a box shadow &#8211; optionally</li>
<li>Repeat this process for active and hover states</li>
</ol>
<p>For sure, making good buttons means doing these steps well. But programmatically, this is pretty damn simple. The difficultly lies in design not code.</p>
<p>With that in mind, let&#8217;s look at how we might use a CSS abstraction language, like <a href="http://fadeyev.net/2010/06/19/lessjs-will-obsolete-css/">LESS</a>, to boil these steps down and make our button code super flexible. But first, let&#8217;s take a look at CSS abstraction languages more generally.</p>
<h3>What&#8217;s a CSS abstraction language?</h3>
<p>An abstraction language is a wrapper that adds powerful functionally to the standard CSS language. Have you ever wanted to set a variable in your stylesheet or do some math? Abstraction languages make this possible.</p>
<p>Now, if you&#8217;re like me, you might be thinking: &#8220;If I need to do multiplication in a stylesheet something&#8217;s gone terribly wrong.&#8221; Keep reading. Maybe you&#8217;ll change your mind.</p>
<h3>How do I use a CSS abstraction language?</h3>
<p>Normally, abstraction languages require a supporting back-end language. This supporting language parses your abstracted code and generates normal, static stylesheets at runtime. Ruby, for example, does exactly this to turn SASS into CSS.</p>
<p>That&#8217;s cool, but for most projects we don&#8217;t need a powerful back-end framework. And there&#8217;s certainly no reason start using one just to make your stylesheets more dynamic. This means, by and large, abstraction languages just aren&#8217;t viable except in large, complicated projects.</p>
<p>But <a href="http://fadeyev.net/2010/06/19/lessjs-will-obsolete-css/">LESS</a> is about to change all that. <a href="http://cloudhead.io/">Alexis Sellier</a> has recently developed a pure JavaScript implementation. This means no back-end language is required. Just follow these simple steps:</p>
<ol class="block_list">
<li>Give your stylesheet a mime type of <span class="code_text">.less</span> rather than <span class="code_text">.css</span></li>
<li>Add an attribute of <span class="code_text">rel=&quot;stylesheet/less&quot;</span> rather than <span class="code_text">rel=&quot;stylesheet&quot;</span>
    </li>
<li>Include the <span class="code_text">less.js</span> script <span class="italic">below</span> all stylesheets in your header.</li>
</ol>
<p>With that finished, your header should include something like:</p>
<div class="code_block">
<pre class="brush: css;">
        &lt;link rel="stylesheet/less" href="buttons.less" type="text/css" charset="utf-8" &gt;
        &lt;script src="less-1.0.30.min.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt;
    </pre>
</div>
<p>And now we have access to some pretty awesome features. Like setting variables and performing operations:</p>
<div class="code_block">
<pre class="brush: css;">
        @pagewrap_width: 970px
        @accent_color: #2BBF26;        

        section {
          @pagewrap_width - 300px
          color: @accent_color - #f0f0f0;
        }
    </pre>
</div>
<p>And that&#8217;s just a few of the awesome features. I encourage you to checkout the <a href="http://fadeyev.net/2010/06/19/lessjs-will-obsolete-css/">details</a> and <a href="http://lesscss.org/">documentation</a>.</p>
<h3>How can we use this to make better buttons?</h3>
<h4><span>1</span> Get a nice looking button.</h4>
<p>Making a nice button can be tricky, so I recommend using the code posted in one of these <a href="http://www.smashingmagazine.com/2009/12/02/pushing-your-buttons-with-practical-css3/">excellent tutorials</a>. But if you&#8217;d rather roll your own, I suggest this dead simple <a href="http://css-tricks.com/examples/ButtonMaker/">button making tool</a>.</p>
<p>Whatever your method, just get some CSS and paste it into your <a href="http://fadeyev.net/2010/06/19/lessjs-will-obsolete-css/">LESS</a> equipped stylesheet. In this example, I&#8217;ll be using this code:</p>
<div class="code_block">
<pre class="brush: css;">
        /* styles for button color */
        .button {
          color: #fef4e9;
          border: solid 1px #da7c0c;
          background: #f78d1d;
          background: -webkit-gradient(linear, left top, left bottom, from(#faa51a), to(#f47a20));
          background: -moz-linear-gradient(top,  #faa51a,  #f47a20);
        }
        .button:hover {
          background: #f47c20;
          background: -webkit-gradient(linear, left top, left bottom, from(#f88e11), to(#f06015));
          background: -moz-linear-gradient(top,  #f88e11,  #f06015);
        }
        .button:active {
          background: -webkit-gradient(linear, left top, left bottom, from(#f47a20), to(#faa51a));
          background: -moz-linear-gradient(top,  #f47a20,  #faa51a);
        }

        /* basic styles for button size, padding, etc. */
        .button {
          display: inline-block;
          outline: none;
          cursor: pointer;
          text-align: center;
          text-decoration: none;
          font-size: @font_size;
          line-height: 100%;
          font-family: Helvetica, Verdana, Arial, sans-serif;
          padding: .55em 2em .55em;
          text-shadow: 0 1px 1px rgba(0,0,0,.3);
          -webkit-border-radius: 0.5em;
          -moz-border-radius: 0.5em;
          border-radius: 0.5em;
          -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2);
          -moz-box-shadow: 0 1px 2px rgba(0,0,0,.2);
          box-shadow: 0 1px 2px rgba(0,0,0,.2);
        }
        .button:hover {
          text-decoration: none;
        }
        .button:active {
          position: relative;
          top: 1px;
        }
    </pre>
</div>
<p>And our buttons will look like:</p>
<p><img src="http://coryschires-blog-post-images.s3.amazonaws.com/dynamic_buttons/blue_buttons.png" /></p>
<h4><span>2</span> Extract the important stuff into variables.</h4>
<p>That&#8217;s a lot of CSS but let&#8217;s focus on what actually matters: font color, border radius, border color, padding, and background gradients. </p>
<p>Let&#8217;s move these values into variables. It&#8217;s a good convention to place them at the top of your stylesheet like so:</p>
<div class="code_block">
<pre class="brush: css;">
        /* basic button variables */
        @background_color: #f78d1d;
        @hover_background_color: #f47c20;
        @border_radius: 0.5em;
        @font_size: 14px;
        @font_color: #fef4e9;
        @button_padding: 0.55em 2em;
        @border_color: #da7c0c;

        /* background color gradients for each state */
        @normal_background_top: #faa51a;
        @normal_background_bottom: #f47a20; 

        @hover_background_top: #f88e11;
        @hover_background_bottom: #f06015; 

        @active_background_top: #f47a20;
        @active_background_bottom: #faa51a;

        /* ...previous css with original values substituted for variables... */
    </pre>
</div>
<p>Now, already that&#8217;s a nice improvement. We can easily make changes to our button styles without having to wade through all that CSS. Want rounder corners? Just increase <span class="code_text">@border_radius</span>.</p>
<h4><span>3</span> Make a good thing better with high school math.</h4>
<p>While we&#8217;ve made an improvement, that still feels like too many configuration options for a simple button. Wouldn&#8217;t it be nice, for example, if we didn&#8217;t have to worry with all those color variations (i.e. border color, background colors, gradients, etc). It would be much better if we could consolidate all those values into a single variable (e.g. <span class="code_text">@button_color</span>).</p>
<p>Let&#8217;s do just that. First, let&#8217;s change <span class="code_text">@background_color</span> to <span class="code_text">@button_color</span>. We&#8217;ll hold this value constant and set all of our other color-related values relative to <span class="code_text">@button_color</span>. This means we&#8217;ll be able to alter one variable &mdash; <span class="code_text">@button_color</span> &mdash; and changes will automatically cascade through related variables. </p>
<p>In case you&#8217;re confused, I&#8217;ll break it down a bit so you can see what&#8217;s going on. We&#8217;re just doing some simple math with hexcodes:</p>
<div class="code_block">
<pre class="brush: css;">
        /* we've already set these variables */
        @background_color: #f78d1d;
        @border_color: #da7c0c;

        /* if we know that: */
            @button_color - @border_color = #1D1111
        /* then high school algebra says: */
            @border_color = @button_color - #1D1111
    </pre>
</div>
<p>So we can use this concept to set all our color values relative <span class="code_text">@button_color</span>. Now our configuration options are looking much leaner:</p>
<div class="code_block">
<pre class="brush: css;">
        /* button configuration options */
        @button_color: #f78d1d;
        @border_radius: 0.5em;
        @font_size: 14px;
        @font_color: #fef4e9;
        @button_padding: 0.55em 2em;

        /* color variables set relative to @button_color.
        You probably don't need to change these. */
        @hover_background_color: @button_color - #031100;
        @border_color: @button_color - #1D1111;

        @normal_background_top: @button_color + #031800;
        @normal_background_bottom: @normal_background_top - #062B00; 

        @hover_background_top: @button_color + #010100;
        @hover_background_bottom: @hover_background_top - #082E08; 

        @active_background_top: @normal_background_bottom;
        @active_background_bottom: @normal_background_top;   

        /* ...previous css with original values substituted for variables... */
    </pre>
</div>
<p>So now we only need to concern ourselves with five clearly named variables. And we can easily change our style to suit different themes. Change the value of <span class="code_text">@button_color</span> to <span class="code_text">#ffb515</span> and you get yellow buttons complete with CCS3 gradients:</p>
<p><img src="http://coryschires-blog-post-images.s3.amazonaws.com/dynamic_buttons/yellow_buttons.png" /></p>
<p>Or change <span class="code_text">@button_color</span> to <span class="code_text">#2daebf</span> and <span class="code_text">@font_size</span> to <span class="code_text">22px</span>:</p>
<p><img src="http://coryschires-blog-post-images.s3.amazonaws.com/dynamic_buttons/orange_buttons.png" /></p>
<p>You get the idea. Changing styles couldn&#8217;t be easier.</p>
<h3>But this is about more than just buttons.</h3>
<p>This is just a trivial example of how <a href="http://fadeyev.net/2010/06/19/lessjs-will-obsolete-css/">LESS</a> can make our stylesheets more dynamic. Imagine, for example, WordPress themes where non-developers could alter the entire color scheme by changing a single variable. Or tweak the layout through something like <span class="code_text">@sidebar_width</span>.</p>
<p>When done well, layouts could even feel a bit like jQuery plugins. Just download the files, change a few configuration options, and you&#8217;re ready to roll. This would be especially useful for stylesheets that aren&#8217;t too application specific &mdash; like wireframe layouts or admin/cms interfaces. </p>
<p>Maybe designers will even start open-sourcing layouts the way developers share plugins? Maybe.</p>
<p><a class="download" href="http://github.com/coryschires/CSS3-Buttons-with-LESS">Download the project from GitHub</a></p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/dynamic-css3-buttons-with-less/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>jQuery swap form value plugin.</title>
		<link>http://coryschires.com/jquery-swap-form-value-plugin/</link>
		<comments>http://coryschires.com/jquery-swap-form-value-plugin/#comments</comments>
		<pubDate>Wed, 09 Jun 2010 06:38:06 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://coryschires.com/jquery-pwap-form-value-plugin/</guid>
		<description><![CDATA[Here's a simple, lightweight plugin to swap default values in a form field. It works with both <span class="code_text">textarea</span> and <span class="code_text">input</span> elements, and runs solidly across browsers.]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a simple, lightweight plugin to swap default values in a form field. It works with both <span class="code_text">textarea</span> and <span class="code_text">input</span> elements, and runs solidly across browsers. For example:</p>
<div class="faux_form" id="swap_value_demo">
<input type="text" name="username" swap_value="username" />
<input type="password" name="password" swap_value="password" />
</div>
<p><!--faux_form--></p>
<h3>How to make it work.</h3>
<p>Just add a swap_value attribute to your element specifying the value you’d like shown in the field: </p>
<div class="code_block">
<pre class="brush: jscript;">
       &lt;input type="text" name="username" swap_value="username" /&gt;
    </pre>
</div>
<p>And call the plugin like this: </p>
<div class="code_block">
<pre class="brush: jscript;">
        $("input[swap_value], textarea[swap_value]").swap_value();
    </pre>
</div>
<p>You can also change the default text colors by passing arguments to the function:</p>
<div class="code_block">
<pre class="brush: jscript;">
        $("input[swap_value], textarea[swap_value]").swap_value({
			normal_color: '#3E474D',
			default_color: '#BCBCBD'
        });
    </pre>
</div>
<h3>Don&#8217;t forget about accessibility.</h3>
<p>For accessibility reasons, you should always include labels for each of your form elements. If you don&#8217;t want labels cluttering up your view, I suggest you hide them:</p>
<div class="code_block">
<pre class="brush: ruby;">
        <label for="First Name" style="display: none;">First Name</label>
        <!-- input element here... -->
    </pre>
</div>
<h3>Some more powerful alternatives.</h3>
<p>There are some similar, although much more powerful, plugins available for swapping form values. If you&#8217;re looking something more fully-featured, I suggest you checkout <a href="http://code.google.com/p/jquery-watermark/" class="new_window">jquery watermark</a>. Also the <a href="http://fuelyourcoding.com/in-field-labels/" class="new_window">in-field labels plugin</a> seems pretty awesome. </p>
<p>Of course, the right choice depends on the needs of your application. Better to go with something simple, if that&#8217;s all you need.</p>
<p><a href="http://github.com/coryschires/swap-value" class="new_window download">Download the project from GitHub</a></p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/jquery-swap-form-value-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to shorten urls with bit.ly in Ruby on Rails.</title>
		<link>http://coryschires.com/how-to-shorten-urls-with-bit-ly-in-ruby-on-rails/</link>
		<comments>http://coryschires.com/how-to-shorten-urls-with-bit-ly-in-ruby-on-rails/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 00:20:44 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[bit.ly]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby-on-Rails]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=307</guid>
		<description><![CDATA[Create retweet links with shortened urls in ruby on rails. Only requires two simple helper methods which you can cut-n-paste into your application.]]></description>
			<content:encoded><![CDATA[<p>First, let&#8217;s make a simple retweet link for our application. To keep our views a little cleaner, we&#8217;ll make a helper method in <span class="code_text">app/helpers/application_helper.rb</span>:</p>
<div class="code_block">
<pre class="brush: ruby;">
        def twitter_url(resource, tweet_text="Check out this article from my-site.com:")
          tweet_url = root_url.chop + url_for(resource)
          "http://twitter.com/home?status=#{tweet_text} #{tweet_url}"
        end
    </pre>
</div>
<p>This method just builds a url to twitter and supplies some default text which you may optionally override by passing a second argument. Call it in your view like this:</p>
<div class="code_block">
<pre class="brush: ruby;">
        <%= link_to "Retweet this post!", twitter_url(@post) %>
    </pre>
</div>
<p>Now, this method works but it would be much better if we could use shortened urls. So let&#8217;s change things a bit in order to use bit.ly &mdash; twitter&#8217;s preferred url shortening service. Before we write any code&#8230; </p>
<ol>
<li>You&#8217;ll need to <a href="http://bit.ly/account/register?rd=/">sign up for bit.ly</a>.</li>
<li>And <a href="http://bit.ly/account/your_api_key">grap your api key</a>.</li>
</ol>
<p>With that info on hand, we&#8217;re ready to interface with the bit.ly api. Let&#8217;s make another helper method also located in <span class="code_text">app/helpers/application_helper.rb</span>:</p>
<div class="code_block">
<pre class="brush: ruby;">
        def shorten_with_bitly(url)
          # build url to bitly api
          user = "insert-your-username"
          apikey = "insert-your-api-key"
          version = "2.0.1"
          bitly_url = "http://api.bit.ly/shorten?version=#{version}&#038;longUrl=#{url}&#038;login=#{user}&#038;apiKey=#{apikey}"

          # parse result and return shortened url
          buffer = open(bitly_url, "UserAgent" => "Ruby-ExpandLink").read
          result = JSON.parse(buffer)
          short_url = result['results'][url]['shortUrl']
        end
    </pre>
</div>
<p>This method uses your credentials to build a url to interface with the bit.ly api. Bitly receives our request and returns a JSON object containing a shortened url. We&#8217;ll parse this object, grab the shortened url, and return it.</p>
<p>Finally, we need to change our initial <span class="code_text">twitter_url</span> method to include url shortening:</p>
<div class="code_block">
<pre class="brush: ruby;">
        def twitter_url(resource, tweet_text="Check out this article from my-site.com:")
          tweet_url = root_url.chop + url_for(resource)
          tweet_url = shorten_with_bitly(tweet_url) if Rails.env.production?

          "http://twitter.com/home?status=#{tweet_text} #{tweet_url}"
        end
    </pre>
</div>
<p>This is identical to our original method except we&#8217;ve added a new line which calls <span class="code_text">shorten_with_bitly</span>. This line overwrites the <span class="code_text">tweet_url</span> variable &mdash; replacing the long url with a shortened version. Finally, we&#8217;ll include a condition to ensure this only happens in production. This saves us from creating a bunch of useless bit.ly links that point to localhost urls.</p>
<h3>Some final points.</h3>
<ul>
<li>
        The <span class="code_text">shorten_with_bitly</span> method borrows heavily form a ruby snippet posted by <a href="http://puneetitengineer.wordpress.com/2009/07/27/minimise-url-in-ruby/">Puneet Pandey</a>. Pandey definitely deserves some credit here.
    </li>
<li>
        If you&#8217;re looking for a more robust way to interface with the bit.ly api, checkout this <a href="http://nasir.wordpress.com/2009/11/26/url-shortener-gem-bitly-api-wrapper-in-ruby/">url shortening gem</a> by Nasir Jamal. I&#8217;ve never used it but appears to be fully featured and well documented.
    </li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/how-to-shorten-urls-with-bit-ly-in-ruby-on-rails/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>First few hours with processing.js.</title>
		<link>http://coryschires.com/first-few-hours-with-processing-js/</link>
		<comments>http://coryschires.com/first-few-hours-with-processing-js/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 05:57:06 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Processing.js]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=296</guid>
		<description><![CDATA[I finally had a chance to check out processing. This language seems to have a lot potential for creating things that would be difficult or impossible with plain javascript...]]></description>
			<content:encoded><![CDATA[<p>I finally had a chance to check out processing. This language seems to have a lot potential for creating things that would be difficult or impossible with plain javascript:</p>
<div class="processing_canvas">
    <canvas datasrc="http://coryschires.com/wp-content/themes/cs-simple/processing/colorful_circle.pjs"></canvas>
</div>
<h3>What is processing.js?</h3>
<p>Processing is an easy-to-learn, open-source programming language for making images, animation, and interactions. Think of it like Flash but without all the nonsense. <a href="http://ejohn.org/" class="new_window">John Resig</a> recently ported the language over to javascript for use on the web. The result &mdash; <a href="http://processingjs.org/">processing.js</a> &mdash; uses javascript to draw shapes and manipulate images on the HTML5 Canvas element.</p>
<h3>How does it work?</h3>
<h4><span>1</span> Download the latest version of processing.js.</h4>
<p>You can download the latest stable release <a href="http://processingjs.org/download">here</a>. The package will contain a few files. First, the processing library which you&#8217;ll need to include in your header like any other javascript library:</p>
<div class="code_block">
<pre class="brush: ruby;">
        &lt;script src="processing-0.4.js"&gt;&lt;/script&gt;
    </pre>
</div>
<p>Next, an example.pjs file. This is where you&#8217;ll write your actual processing code. You&#8217;ll need need to reference this file somewhere in the body of your webpage: </p>
<div class="code_block">
<pre class="brush: ruby;">
        &lt;canvas datasrc="example.pjs"&gt;&lt;/canvas&gt;
    </pre>
</div>
<h4><span>2</span> Create a setup() block to hold your basic configuration logic.</h4>
<p>A <span class="code_text">setup()</span> block holds your basic configuration logic (i.e. the stuff you want to happen one time when the file is loaded). A simple <span class="code_text">setup()</span> block might look like this:</p>
<div class="code_block">
<pre class="brush: java;">
        void setup() {
        	size(255,255);
        	background(224); // light gray
        }
    </pre>
</div>
<h4><span>3</span> And create a draw() block to manage your animation.</h4>
<p>You place your animation code inside a <span class="code_text">draw()</span> block. This code will run as a continuous loop. This means it can be response to interactions, such as mouse position. This little block, for example, will draw a thin black line based on mouse position:</p>
<div class="code_block">
<pre class="brush: java;">
        void draw() {
        	// set line color to black
        	stroke(0);
        	// draw line between previous and new mouse coordinates
        	line(pmouseX,pmouseY, mouseX,mouseY);
        }
    </pre>
</div>
<h3>Where can I learn more?</h3>
<p>There are not many processing.js specific resources. But don&#8217;t worry. Both processing.js and the standard processing language use the same java-like syntax. This means you can freely mix-n-match resources from either project.</p>
<p>With that in mind, here&#8217;s a few leads:</p>
<ul>
<li>
        The <a href="http://processingjs.org/">processing.js homepage</a> has an excellent <a href="http://processingjs.org/learning">learning section</a> as well as a fairly extensive <a href="http://processingjs.org/reference">reference library</a>.
    </li>
<li>
        Casey Reas and Ben Fry, the creators of processing were nice enough to write a book. It&#8217;s available from the MIT press: <a href="http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&#038;tid=11251">Processing: A Programming Handbook for Visual Designers and Artists</a>
    </li>
<li>
        You might also checkout <a href="http://www.learningprocessing.com/">Learning Processing</a>. It&#8217;s a little easier to work through &mdash; especially if you&#8217;re new to programming.
    </li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/first-few-hours-with-processing-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

