url snippets

Split a URL into protocol, domain, port and URI using regular expressions

Tagged java, url, regex  Languages java
// Split URL into protocol, domain, port and URI
Pattern pattern = Pattern.compile("(https?://)([^:^/]*)(:\\d*)?(.*)?");
Matcher matcher = pattern.matcher(url);

matcher.find();

String protocol = matcher.group(1);            
String domain   = matcher.group(2);
String port     = matcher.group(3);
String uri      = matcher.group(4);

SEO optimized image URLs with the Paperclip Rails plugin

Tagged paperclip, rails, ruby, plugin, seo, url  Languages ruby

Create config/initializers/paperclip.rb:

# http://wiki.github.com/thoughtbot/paperclip/interpolations
Paperclip.interpolates :to_param do |attachment, style|
  attachment.instance.to_param
end

In the model:

has_attached_file :image, 
                    :path => ":rails_root/public/images:to_param/:style/:basename.:extension",
                    :url => "/images:to_param/:style/:basename.:extension",
                    :styles => { :large  => "250x360#",
                                 :medium => "150x230#",
                                 :small  => "110x150#" }

Instead of URLs like:

/images/products/249/large/temp.jpg

You can get a URL based on, for example, a permalink as in the example above. In my case I get URLs like this:

/images/games/nintendo-wii/large/super-mario-galaxy.jpg

How to make a clickable link inside a NSTextField and Cocoa

Tagged clickable, url, nstextfield, cocoa  Languages objectivec

From How do I embed a hyperlink inside an NSTextField or NSTextView?

NSAttributedString+Hyperlink.h

#import <Cocoa/Cocoa.h>

@interface NSAttributedString (Hyperlink)
+(id)hyperlinkFromString:(NSString*)inString withURL:(NSURL*)aURL;
@end

NSAttributedString+Hyperlink.m:

#import "NSAttributedString+Hyperlink.h"


@implementation NSAttributedString (Hyperlink)
+(id)hyperlinkFromString:(NSString*)inString withURL:(NSURL*)aURL
{
    NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString: inString];
    NSRange range = NSMakeRange(0, [attrString length]);
    
    [attrString beginEditing];
    [attrString addAttribute:NSLinkAttributeName value:[aURL absoluteString] range:range];
    
    // make the text appear in blue
    [attrString addAttribute:NSForegroundColorAttributeName value:[NSColor blueColor] range:range];
    
    // next make the text appear with an underline
    [attrString addAttribute:
     NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSSingleUnderlineStyle] range:range];
    
    [attrString endEditing];
    
    return [attrString autorelease];
}
@end

This code sets the contents of the NSTextField to a URL:

#import "NSAttributedString+Hyperlink.h"

[textURL setAllowsEditingTextAttributes: YES];
[textURL setSelectable: YES];
    
NSURL* url = [NSURL URLWithString:@"http://www.apple.com"];
    
NSMutableAttributedString* string = [[NSMutableAttributedString alloc] init];
[string appendAttributedString: [NSAttributedString hyperlinkFromString:@"Apple Computer" withURL:url]];
    
[textURL setAttributedStringValue: string];

How to fix "bad URI(is not URI?)"

Tagged ruby, uri, url, parse  Languages ruby

This URL contains special characters, which Ruby can't handle:

>> URI.parse 'http://www.yr.no/sted/Finland/Västra_Finland/Askainen/varsel.xml'
URI::InvalidURIError: bad URI(is not URI?): http://www.yr.no/sted/Finland/Västra_Finland/Askainen/varsel.xml
    from /usr/local/lib/ruby/1.8/uri/common.rb:436:in split'
    from /usr/local/lib/ruby/1.8/uri/common.rb:485:in parse'
    from (irb):5

Your browser can probably open the URL. To fix this error encode the URL before handing it to the parse method:

URI.parse(URI.encode('http://www.yr.no/sted/Finland/Västra_Finland/Askainen/varsel.xml'))
=> #<URI::HTTP:0x18bfb40 URL:http://www.yr.no/sted/Finland/V%C3%A4stra_Finland/Askainen/varsel.xml>

How to parse request parameters with JavaScript

Tagged url, parse, javascript, jquery, request, parameters  Languages javascript

Code:

var Request = {
    parameter: function(name) {
      return this.parameters()[name];
    },
    parameters: function(uri) {
      var i, parameter, params, query, result;
      result = {};
      if (!uri) {
        uri = window.location.search;
      }
      if (uri.indexOf("?") === -1) {
        return {};
      }
      query = uri.slice(1);
      params = query.split("&");
      i = 0;
      while (i < params.length) {
        parameter = params[i].split("=");
        result[parameter[0]] = parameter[1];
        i++;
      }
      return result;
    }
  };

Examples:

// ?query=test
var query = Request.parameter('query');

var parameters = Request.parameters();
// This works too
var query = parameters.query;
// And this
var query = parameters['query'];

// Replacing a parameter is easy with jQuery
parameters Request.parameters();
// change sort order
parameters.order = 'new-world-order'
new_parameters = $.param(parameters)
url = window.location.pathname + "?" + new_parameters

SEO optimizing CarrierWave URLs

Tagged filename, url, carrierwave, seo  Languages apacheconf
class ProductImageUploader < CarrierWave::Uploader::Base

  def store_dir
    "product"
  end

  def filename
    ext = File.extname(original_filename) if original_filename
    "#{model.name.parameterize}#{ext}"
  end
end

Localizing URLs and Rails3 routes

Tagged i18n, seo, routes, rails3, url  Languages ruby

If you need to support localized URLs in a Rails application, you have at least two plugins to choose from: * i18n_routing NOTE: doesn't seem to work with Rails 3.2.8 * rails-translate-routes

I recommend the rails-translate-routes plugin because it allows me to create exactly the URLs I need.

For example, if these are the localized URLs I need:

http://xxx.com/news
http://yyy.com/uutiset
http://zzz.com/nyheter

Validating URLs in Rails

Tagged url, active_record, validation, rails  Languages ruby

Minimalist implementation

A naïve implementation:

validates_format_of :website, :with => URI::regexp(%w(http https))

via http://mbleigh.com/2009/02/18/quick-tip-rails-url-validation.html

Full-featured and reusable implementation

A more full-featured and reusable example using the Addressable gem (app/validators/uri_validator.rb):

require 'addressable/uri'

#
# Validates URLs.
#
# @param options[:allow_uri] If true, validates only URI part of URL and skips host and scheme.
# @param options[:message] Error message.
# @param options[:allowed_protocols] Allowed protocols, e.g. [:http, :https].
#
class UriValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    uri = parse_uri(value)
    if !uri
      record.errors[attribute] << generic_failure_message
    elsif !allowed_protocols.include?(uri.scheme)
      record.errors[attribute] << "must begin with #{allowed_protocols_humanized}"
    end
  end

private

  def generic_failure_message
    options[:message] || "is an invalid URL"
  end

  def allowed_protocols_humanized
    allowed_protocols.to_sentence(:two_words_connector => ' or ')
  end

  def allowed_protocols
    @allowed_protocols ||= options.fetch(:allowed_protocols, ['http', 'https'])
  end

  def parse_uri(value)
    uri = Addressable::URI.parse(value)
    uri.scheme && uri.host && uri.to_s == value && uri
  rescue URI::InvalidURIError, Addressable::URI::InvalidURIError, TypeError
  end
end

Tests:

require 'spec_helper'

describe UriValidator do
  let(:subject) do
    Class.new do
      include ActiveModel::Validations
      attr_accessor :url
      validates :url, uri: true
    end.new
  end

  VALID_URL = [ 'http://www.google.com',
                'http://.com', # NOTE: Addressable thinks this is valid
                'http://google' ]
  VALID_URL.each do |valid_url|
    it "accepts a valid URL (#{valid_url})" do
      subject.url = valid_url
      assert subject.valid?
      subject.errors.full_messages.should == []
    end
  end

  INVALID_URL = ['http://ftp://ftp.google.com',
                 'http://ssh://google.com',
                 '//www.google.com',
                 'www.google.com',
                 'google.com',
                 'http:/www.google.com',
                 '<>hi' ]
  INVALID_URL.each do |invalid_url|
    it "#{invalid_url} is an invalid url" do
      subject.url = invalid_url
      subject.valid?
      binding.pry if subject.valid?
      subject.errors.should have_key(:url)
      subject.errors[:url].should include("is an invalid URL")
    end
  end

  INVALID_PROTOCOL = [ 'ftp://ftp.google.com',
                       'ssh://google.com' ]
  INVALID_PROTOCOL.each do |invalid_url|
    it "#{invalid_url} is an invalid url" do
      subject.url = invalid_url
      subject.valid?
      subject.errors.should have_key(:url)
      subject.errors[:url].should include("must begin with http or https")
    end
  end
end

Code based on http://gist.github.com/bf4/5320847.