util.lua 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. -- Copyright 2008 Steven Barth <steven@midlink.org>
  2. -- Copyright 2017 Matthias Schiffer <mschiffer@universe-factory.net>
  3. -- Licensed to the public under the Apache License 2.0.
  4. local io = require "io"
  5. local table = require "table"
  6. local tparser = require "gluon.web.template.parser"
  7. local nixio = require "nixio"
  8. local fs = require "nixio.fs"
  9. local getmetatable, setmetatable = getmetatable, setmetatable
  10. local tostring, pairs = tostring, pairs
  11. module "gluon.web.util"
  12. --
  13. -- Class helper routines
  14. --
  15. -- Instantiates a class
  16. local function _instantiate(class, ...)
  17. local inst = setmetatable({}, {__index = class})
  18. if inst.__init__ then
  19. inst:__init__(...)
  20. end
  21. return inst
  22. end
  23. -- The class object can be instantiated by calling itself.
  24. -- Any class functions or shared parameters can be attached to this object.
  25. -- Attaching a table to the class object makes this table shared between
  26. -- all instances of this class. For object parameters use the __init__ function.
  27. -- Classes can inherit member functions and values from a base class.
  28. -- Class can be instantiated by calling them. All parameters will be passed
  29. -- to the __init__ function of this class - if such a function exists.
  30. -- The __init__ function must be used to set any object parameters that are not shared
  31. -- with other objects of this class. Any return values will be ignored.
  32. function class(base)
  33. return setmetatable({}, {
  34. __call = _instantiate,
  35. __index = base
  36. })
  37. end
  38. function instanceof(object, class)
  39. while object do
  40. if object == class then
  41. return true
  42. end
  43. local mt = getmetatable(object)
  44. object = mt and mt.__index
  45. end
  46. return false
  47. end
  48. --
  49. -- String and data manipulation routines
  50. --
  51. function pcdata(value)
  52. return value and tparser.pcdata(tostring(value))
  53. end
  54. function contains(table, value)
  55. for k, v in pairs(table) do
  56. if value == v then
  57. return k
  58. end
  59. end
  60. return false
  61. end
  62. --
  63. -- System utility functions
  64. --
  65. function exec(command)
  66. local pp = io.popen(command)
  67. local data = pp:read("*a")
  68. pp:close()
  69. return data
  70. end
  71. function uniqueid(bytes)
  72. local rand = fs.readfile("/dev/urandom", bytes)
  73. return nixio.bin.hexlify(rand)
  74. end
  75. function libpath()
  76. return '/lib/gluon/web'
  77. end