samedi 3 janvier 2015

Create object from string in Coffee script

I'm sure there is a much cleaner (and coffee native) way to do this.


What I need is to go from



background: url(../assets/logos/logos.jpg) no-repeat; background-position: 0px -50px; height: 50px; width: 250px; margin: 0 auto;


into



{ background: 'url(../assets/logos/logos.jpg) no-repeat',
'background-position': '0px -50px',
height: '50px',
width: '250px',
margin: '0 auto' }


which is basically



  • take a string

  • split it by ;

  • split them by :

  • first() is the key and second is the value


Here is the code I currently have to do this conversion



items = {}
log style
for item in style.split(';')
if (item)
items[item.split(':').first().trim()] =item.split(':').second().trim()
log items


For reference here is where this code snippet fits (I'm creating a unit test to test CSS)



check_Generic_Footer_Css = (html, baseUrl, next)->
juice = require('juice')
cheerio = require('cheerio')
juice.juiceContent html, { url: baseUrl}, (err, cssHtml)->
$css = cheerio.load(cssHtml)
footer_Attr = $css('#footer #footer-img #si-logo').attr()
footer_Attr.assert_Is { id: 'si-logo'
, style: 'background: url(../assets/logos/logos.jpg) no-repeat; background-position: 0px -50px; height: 50px; width: 250px; margin: 0 auto;' }

style = footer_Attr.style
items = {}
log style
for item in style.split(';')
if (item)
items[item.split(':').first().trim()] =item.split(':').second().trim()
log items

background =items['background']

items['background'].assert_Is('url(../assets/logos/logos.jpg) no-repeat' )
next()

Aucun commentaire:

Enregistrer un commentaire