winton / stasis

Static sites made powerful
http://stasis.me
MIT License
679 stars 56 forks source link

Using relative paths in development mode. #16

Closed budu closed 12 years ago

budu commented 12 years ago

I didn't find how to get relative paths for my assets in development mode while retaining the ability to use absolute paths in my code so I came up with my own solution. I'm using a simple helper that I put in the root controller:

helpers do

  def depth
    root = File.dirname __FILE__
    relative_path = Dir.pwd.sub root, ''
    relative_path.count File::Separator
  end

  def asset(path)
    return path unless ENV['MODE'] == 'dev' && path[0] == '/'

    if depth == 0
      '.'
    else
      depth.times.map { '..' }.join(File::Separator)
    end + path
  end

end

This could be a worthy addition to Stasis I think, but it could probably be done in a better way in Stasis internals.

br commented 12 years ago

Hello. I'm not sure I understand your original problem. Could you expand upon that, maybe with some code examples?

budu commented 12 years ago

Say I have an image in a HTML page in a subdirectory of my static site and that all my images are in the /images/ directory, I'd do:

%img{ src: '../images/foo.png' }

But using relative path eveywhere is error prone and become a real mess when I move things around, that why we normally use absolute path in most case with dynamic web applications, like:

%img{ src: '/images/foo.png' }

With a static website though, I'm not using a web server during development so using absolute path doesn't work. One trick I've used in other similar project is to make a helper that automatically generate the relative path from an absolute one, that is the code I'm showing in this ticket. With it I can use:

%img{ src: asset('/images/foo.png') }

and get the best of both worlds.

winton commented 12 years ago

Ah I see what you mean. Thank you for the explanation. Will give some thought to this.

winton commented 12 years ago

I decided that the solution to this was to provide a web server in dev mode. Start a web server on port 3000 like so:

stasis -d 3000

See: http://stasis.me/#usage